Evc vc String Conversion Processing

Source: Internet
Author: User

1. Define the macro in the header file;

# Define UNICODE # define _ UNICODE // char buf [128]; memset (buf, 0,128 ); strcpy (buf, ""); WCHAR pCName [128]; memset (pCName,); MultiByteToWideChar (CP_THREAD_ACP, MB_USEGLYPHCHARS, buf, strlen (buf), pCName, 128 );

To convert WCHAR to CHAR, use
WideCharToMultiByte

//////////////////////////

2. Convert char to wchar

const  char  *pFilePathName  =  "c:\\aa.dll"; int  nLen  =  strlen(pFilePathName)  +  1; int  nwLen  =  MultiByteToWideChar(CP_ACP,  0,  pFilePathName, nLen,  NULL,  0); TCHAR  lpszFile[256]; MultiByteToWideChar(CP_ACP,  0,  pFilePathName,  nLen,  lpszFile, nwLen); 

3. Convert wchar to char

char  *pFilePathName; TCHAR  lpszFile[256]; _tcscpy(lpszFile,  _T("c:\\aa.dll")); int  nLen  =  wcslen(wstr)+1; WideCharToMultiByte(CP_ACP,  0,  lpszFile,  nLen,  pFilePathName, 2*nLen,  NULL,  NULL);
 

Char * And CString Conversion
CString is a special C ++ object, which contains three values: A pointer pointing to a data buffer, and a valid string in the buffer (it is not accessible and is located in
A hidden area under the CString address) and a buffer length.
The valid characters can be any number between 0 and the maximum buffer length minus 1 (because the string ends with a NULL character ). Characters and buffer length are cleverly hidden.

(1) convert char * To CString
If char * is converted to CString, you can use CString: Format in addition to direct value assignment. For example:

Char chArray [] = "Char test"; TCHAR * p = _ T ("Char test"); (or? LPTSTR p = _ T ("Char test");) CString theString = chArray; theString. Format (_ T ("% s"), chArray); theString = p;

(2) convert CString to char *

If the CString type is converted to the char * (LPSTR) type, the following three methods are often used:

Method 1: use forced conversion. For example:

       CString theString( (_T("Char test "));       LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;

Method 2: Use strcpy. For example:

       CString theString( (_T("Char test "));       LPTSTR lpsz = new TCHAR[theString.GetLength()+1];       _tcscpy(lpsz, theString);

It should be noted that the second parameter of strcpy (or _ tcscpy of the value to be moved) is const wchar_t * (Unicode) or const char * (ANSI ), the system compiler will automatically convert it.

Method 3: Use CString: GetBuffer.
If you need to modify the content in CString, there is a special method that can be used, that is, GetBuffer, which is used to return a writable buffer pointer.
If you only want to modify characters or truncate strings, for example:

  CString s(_T("Char test "));  LPTSTR p = s.GetBuffer();  LPTSTR dot = strchr(p, ''.'');

// Add the code using p here

If (p! = NULL) * p = _ T ('\ 0'); s. ReleaseBuffer (); // release immediately after use, so that other CString member functions can be used.
In the range between GetBuffer and ReleaseBuffer, you must not use any method of the buffer CString object you want to operate on. Because the integrity of the CString object is not guaranteed before ReleaseBuffer is called.
 

Relationship and difference between CString, BSTR, and LPCTSTR

CString is a dynamic TCHAR array, and BSTR is a string in a proprietary format (it needs to be manipulated using the functions provided by the system. The LPCTSTR is just a constant TCHAR pointer.

CString is a completely independent class, dynamic TCHAR array, and encapsulates operators such as + and string operation methods.

typedef OLECHAR FAR* BSTR;typedef const char * LPCTSTR;

Representation of various strings in vc ++
First, char * is a pointer to an ANSI character array, where each character occupies 8 bits (valid data is to remove the other seven bits), which is consistent with the traditional C, C ++ compatibility.
LP indicates a long pointer ). LPSTR is a pointer to an ANSI character array ending with '\ 0'. It can be used interchangeably with char *, and LPSTR is often used in win32.
The 'C' added in the LPCSTR indicates "CONSTANT" (CONSTANT), indicating that this data type instance cannot be changed by using its API function. In addition, it is equivalent to LPSTR.
1. LP indicates a long pointer. In win16, there is a difference between a long pointer (LP) and a short pointer (P). In win32, there is no difference, both 32-bit. therefore, the LP and P here are equivalent.
2. C Indicates const
3. What is T? We know that TCHAR is wchar_t in Unicode mode and compiled into char in general.

In order to meet the international needs of the program code, the industry has introduced the Unicode Standard, which provides a simple and consistent expression of the string method, all characters in the byte is a 16-bit value, the number of characters can also meet the encoding requirements of almost all written language characters in the world. Unicode (type: wchar_t) is an encouraging practice during development.
This produces LPWSTR and LPCWSTR. Their meanings are similar to LPSTR and LPCSTR, except that the character data is a 16-bit wchar_t instead of a char.
In order to realize the common use of the two types of encoding, TCHAR is defined as follows:
If _ UNICODE is defined, the Declaration is as follows:
Typedef wchar_t TCHAR;
If _ UNICODE is not defined, the Declaration is as follows:
Typedef char TCHAR;
The meaning in LPTSTR and LPCTSTR is that each character is such a TCHAR.
The characters in the CString class are declared as TCHAR type. It provides an encapsulated class for your convenience.

LPCTSTR:#ifdef _UNICODEtypedef const wchar_t * LPCTSTR;#elsetypedef const char * LPCTSTR;#endif

Conversion of common VC Data Types
First, some common types of variables are defined to illustrate

Int I = 100; long l = 2001; float f = 300.2; double d = 12345.119; char username [] = "papaya"; char temp [200]; char * buf; CString str; _ variant_t v1; _ bstr_t v2;

1. convert other data types to strings
Short INTEGER (int)
Itoa (I, temp, 10 );
// Convert I to a string and put it into temp. the last digit indicates decimal.
Itoa (I, temp, 2); // Binary Conversion
Long (long)
Ltoa (l, temp, 10 );

2. Obtain the pointer to the string from other variables containing the string
CString variable
Str = "2008 Beijing Olympics ";
Buf = (LPSTR) (LPCTSTR) str;
_ Variant_t variable of the BSTR type
V1 = (_ bstr_t) "programmer ";
Buf = _ com_util: ConvertBSTRToString (_ bstr_t) v1 );
Iii. Convert strings to other data types
Strcpy (temp, "123 ");
Short INTEGER (int)
I = atoi (temp );
Long (long)
L = atol (temp );
Floating Point (double)
D = atof (temp );
4. convert other data types to CString
Use the CString member function Format for conversion. For example:
INTEGER (int)
Str. Format ("% d", I );
Float)
Str. Format ("% f", I );
Data Types supported by CString constructors, such as string pointers (char *), can be directly assigned values.
Str = username;
V. BSTR, _ bstr_t and CComBSTR
CComBSTR and _ bstr_t are encapsulation of BSTR, and BSTR is a 32-bit pointer to a string.
Char * can be converted to BSTR as follows: BSTR
B = _ com_util: ConvertStringToBSTR ("data ");
// Add the header file comutil. h before use.
Otherwise, use char * p = _ com_util: ConvertBSTRToString (B );

6. VARIANT, _ variant_t, and COleVariant
For the VARIANT Structure, refer to the definition of the tagVARIANT struct in the header file VC98 \ Include \ OAIDL. H.
Assign a value to the VARIANT variable: assign a value to the vt member to specify the data type, and then assign a value to the variable of the same data type in the union structure. For example:

VARIANT va; int a = 2001; va. vt = VT_I4; // indicates? Ming? Whole? Type? Number? Data? Va. lVal = a; // assigned? Value?

For VARIANT that is not immediately assigned a value, it is best to initialize with Void VariantInit (variantarg far * pvarg); in essence, the vt is set to VT_EMPTY, the following table lists the correspondence between vt and common data:
Unsigned char bVal; VT_UI1
Short iVal; VT_I2
Long lVal; VT_I4
Float fltVal; VT_R4
Double dblVal; VT_R8
VARIANT_BOOL boolVal; VT_BOOL
SCODE scode; VT_ERROR
CY cyVal; VT_CY
DATE date; VT_DATE
BSTR bstrVal; VT_BSTR
IUnknown FAR * punkVal; VT_UNKNOWN
IDispatch FAR * pdispVal; VT_DISPATCH
Safearray far * parray; VT_ARRAY | *
Unsigned char FAR * pbVal; VT_BYREF | VT_UI1
Short FAR * piVal; VT_BYREF | VT_I2
Long FAR * plVal; VT_BYREF | VT_I4
Float FAR * pfltVal; VT_BYREF | VT_R4
Double FAR * pdblVal; VT_BYREF | VT_R8
VARIANT_BOOL FAR * pboolVal; VT_BYREF | VT_BOOL
Scode far * pscode; VT_BYREF | VT_ERROR
Cy far * pcyVal; VT_BYREF | VT_CY
Date far * pdate; VT_BYREF | VT_DATE
Bstr far * pbstrVal; VT_BYREF | VT_BSTR
IUnknown FAR * ppunkVal; VT_BYREF | VT_UNKNOWN
IDispatch FAR * ppdispVal;
VT_BYREF | VT_DISPATCH
Safearray far * pparray; VT_ARRAY | *
Variant far * pvarVal; VT_BYREF | VT_VARIANT
Void FAR * byref; VT_BYREF

_ Variant_t is the encapsulation class of VARIANT, and its value assignment can be forced type conversion. Its constructor will automatically process these data types.
For example:
Long l = 222;
Int I = 100;
_ Variant_t lVal (l );
LVal = (long) I;
The use of COleVariant is basically the same as that of the _ variant_t method. See the following example:
COleVariant v3 = "string", v4 = (long) 1999;
CString str = (BSTR) v3.pbstrVal;
Long I = v4.lVal;

VII. Others
During message processing, we often need to split WPARAM, LPARAM, and other 32-bit data (DWORD) into two 16-bit data (WORD), for example:
For a 16-bit data (WORD), we can use the same method to break down the high and low 8-bit data (BYTE), for example:
WORD wValue;
BYTE loValue = LOBYTE (wValue); // get 8 bits
BYTE hiValue = HIBYTE (wValue); // The value is 8 bits in height.

How to assign a variable of the CString type to a variable of the char * type
1. GetBuffer function:
Use the CString: GetBuffer function.

char *p;CString str="hello";p=str.GetBuffer(str.GetLength());str.ReleaseBuffer();

When converting CString to char *

CString str ("aaaaaaa"); strcpy (str. GetBuffer (10), "aa"); str. ReleaseBuffer ();
Call GetBuffer (int n) when we need a character array, where n is the length of the character array we need. Call ReleaseBuffer () immediately after use ();
It is also important that you do not use char * Where const char * can be used *
2. memcpy:
CString mCS=_T("cxl");char mch[20];memcpy(mch,mCS,20);

3. Use LPCTSTR for forced conversion: Do not use it whenever possible
char *ch;CString str;ch=(LPSTR)(LPCTSTR)str;CString str = "good";char *tmp;sprintf(tmp,"%s",(LPTSTR)(LPCTSTR)str);4、CString Msg;Msg=Msg+"abc";LPTSTR lpsz;lpsz = new TCHAR[Msg.GetLength()+1];_tcscpy(lpsz, Msg);char * psz;strcpy(psz,lpsz);

CString class to const char * Conversion
Char a [100];
CString str ("aaaaaa ");
Strncpy (a, (LPCTSTR) str, sizeof ());
Or:
Strncpy (a, str, sizeof ());
The preceding two methods are correct. Because the second parameter type of strncpy is const char *, the compiler automatically converts the CString class to const char *.
CString to LPCTSTR (const char *)
CString cStr;
Const char * maid = (lpctStr) cStr;
Convert the string type to the string type
Maid;
CString cStr = lpctStr;
Assign a char * type variable to a CString type variable.
Values can be assigned directly, for example:
CString myString = "This is a test ";
You can also use constructors, such:
CString s1 ("Tom ");
Assign a variable of the CString type to a variable of the char [] type (string ).
1. sprintf () function

CString str = "good ";
Char tmp [200];
Sprintf (tmp, "% s", (LPCSTR) str );
This forced conversion is equivalent to (LPTSTR) (LPCTSTR) str
When the CString class variables need to be converted to (char *), use (LPTSTR) (LPCTSTR) str
However, the LPCTSTR is const char *, that is, the resulting string cannot be written! It is extremely dangerous to forcibly convert it to LPTSTR to remove const!
If you don't care, you will be finished! To obtain char *, use GetBuffer () or GetBufferSetLength (). Call ReleaseBuffer () after use ().
2. strcpy () function
CString str;
Char c [256];
Strcpy (c, str );
Char mychar [1024];
CString source = "Hello ";
Strcpy (char *) & mychar, (LPCTSTR) source );

Use of CString
1. Specify CString Parameters
For most functions that require string parameters, it is best to specify the form parameter in the function prototype as a pointing character (LPCTSTR)
Instead of the const pointer of CString.
When you specify a parameter as a const pointer to a character, you can pass the pointer to a TCHAR array (such as a string ["hi"
There "]) or passed to the CString object.
The CString object is automatically converted to the LPCTSTR. Any place that can use the LPCTSTR can also be used
CString object.
2. If a parameter is not modified, the parameter is also specified as a constant string reference (const CString &).

If the function needs to modify the string, delete the const modifier. If the default value is null, initialize it as a Null String [""], as shown below:
Void AddCustomer (const CString & name, const
CString & address, const CString & comment = "");
3. For most function results, return the CString object by value.

Basic string operations
Many advanced Languages provide operators or standard library functions for basic string operations.
To facilitate the description, first define several related variables:
Char s1 [20] = "dir/bin/appl", s2 [20] = "file. asm", s3 [30], * p;
Int result;

The following describes the basic operations of strings in C language.
1. Obtain the string length
Int strlen (char * s); // evaluate the length of string s
[Example] printf ("% d", strlen (s1); // output the string length of s1 12
2. String Replication
Char * strcpy (char
* To, * from); // copy the from string to string and return the pointer at the beginning of the to string.
[Example] strcpy (s3, s1); // s3 = "dir/bin/appl", s1 string unchanged

3. Join
Char * strcat (char * to, char
* From); // copy the from string to the end of the string,
// Returns the pointer at the beginning of the to string.
[Example] strcat (s3, "/"); // s3 = "dir/bin/appl /"
Strcat (s3, s2 );
// S3 = "dir/bin/appl/file. asm"
4. String comparison
Int strcmp (char * s1, char * s2); // compare the sizes of s1 and s2,
// When s1 <s2, s1> s2 and s1 = s2, return values smaller than 0, greater than 0, and equal to 0, respectively.
[Example] result = strcmp ("baker", "Baker ");
// Result> 0
Result = strcmp ("12", "12 ");
// Result = 0
Result = strcmp ("Joe", "joseph ")
// Result <0
5. Character locating
Char * strchr (char * s, char c); // locate the first occurrence of c in string s,
// If it is found, the location is returned; otherwise, NULL is returned.
[Example] p = strchr (s2, '.'); // p points to the position after "file ".
If (p) strcpy (p, ". cpp"); // s2 = "file. cpp"
Note:
① The above operations are the most basic, among which the last four operations are also variant forms: strncpy, strncath and strnchr.
② For other string operations, see <string. h> of C. In different advanced languages, the types and symbols of string operations are different.
③ Other string operations can generally be combined by these basic operations
[Example] The Sub-string operation can be implemented as follows:
Void substr (char * sub, char * s, int pos, int
Len ){
// S and sub are character arrays. sub is used to return the substring whose length is len starting from the second pos character of string s.
// 0 <= pos <= strlen (s)-1, and the array sub can contain at least len + 1 characters.
If (pos <0 | pos> strlen (s)-1 | len <0)
Error ("parameter error! ");
Strncpy (sub, & s [pos], len );
// Copy up to len characters to sub from s [pos]

Convert CString type to int type

The simplest way to convert data of the CString type to an integer type is to use a standard string to an Integer Conversion routine.
Although you usually suspect that using the _ atoi () function is a good choice, it is rarely the right choice. If you want to use Unicode characters, you should use _ ttoi (), which is compiled into _ atoi () in the ANSI coding system (), in the Unicode encoding system, encode it into _ wtoi (). You can also consider using _ tcstoul () or _ tcstol (), which can convert strings into any hexadecimal long integers (such as binary, octal, decimal, or hexadecimal ), the difference is that the converted data is unsigned, while the converted data is unsigned. See the following example.
CString hex = _ T ("FAB ");

CString decimal = _ T ("4011 ");

ASSERT (_ tcstoul (hex, 0, 16) = _ ttoi (decimal ));

CString Format String

Unlike using the sprintf () function or wsprintf () function to Format a string, it is better to use the Format () method of the CString object:
CString s; s. Format (_ T ("The total is % d"), total );

The advantage of using this method is that you don't have to worry about whether the buffer for storing formatted data is large enough. This is done by the CString class for you. Formatting is the most common technique to convert other data not of the string type to the CString type. For example, to convert an integer to the CString type, you can use the following method:
CString s; s. Format (_ T ("% d"), total );

In EVC, When I convert CString to Char *, I can write it like this.

# Include <atlconv. h>
... USES_CONVERSION;
CString str = "Cstring ";
Char * p;
P = (char *) W2A (LPCTSTR) str );

Or write it like this.

CString strDemo;

Char AnsiString [MAX_PATH] = {0 };
Wcstombs (AnsiString, (LPTSTR) (LPCTSTR) strDemo, strDemo. GetLength ());

Or write it like this.

Char * = (LPSTR) (LPCTSTR) CString;
Const char * = (LPCSTR) (LPCTSTR) CString;

Or write it like this.

CString strFilePath;
Char FilePath [256];
Memset (FilePath, 0,256 );
StrFilePath = "hello world ";
WideCharToMultiByte (CP_ACP, 0, strFilePath,-1, FilePath, 256,
NULL, NULL );
...
Or write it like this.

First obtain the char buffer size, and then convert it through WideCharToMultiByte
CString strConvert;
Char pchBuffer;
Int iSize;
ISize = WideCharToMultiByte (CP_ACP, 0, strFilePath. GetBuffer (0),-1,
NULL, 0, NULL, NULL );
PchBuffer = new char [iSize * 2 + 1];
If (pchBuffer! = NULL)
{
Memset (pchBuffer, 0, (iSize * 2 + 1) * sizeof (char ));
}
WideCharToMultiByte (CP_ACP, 0, strFilePath. GetBuffer (0),-1,
PchBuffer, (iSize * 2 + 1), NULL, NULL );

Introduction to EVC Chinese string operations
In a sense, EVC is equivalent to a subset of VC. Most EVC functions are available as well as VC functions, whereas EVC does not. In VC, It is very convenient to operate strings, because WINDOWS's word processing capabilities are really powerful, and it supports multiple character sets. If we use a CString str = "hello", we need to enter the Chinese string we want. In EVC, this situation has changed because WINCE's word processing capability is not powerful enough. It shows it as UNICODE encoding in the processing of Chinese characters, therefore, we need to use UNICODE encoding to manage Chinese strings in EVC. The following compares the Processing Methods of the EVC Chinese string with the VC string processing in WINDOWS.

I. Definition of Chinese strings
1. if we define a Chinese string in VC, we can use CString str = "hello" or LPCTSTR str = "hello ".
2. If you want to define a Chinese string in EVC, you can use the following method: CString str = _ T ("hello") or LPCTSTR str = "hello ", here, the LPCTSTR represents a UNICODE string in EVC. It is worth noting that in the _ T () Macro, only constants can be filled in brackets, and variables cannot be filled in.
Ii. String operations
1. To copy strings in VC, perform the following operations:
Char s [20];
CString str = "hello ";
Strcpy (s, str );
In EVC, we cannot do this. First, we should use the dual-byte pointer wchar_t to define the Chinese array, and the copy function cannot use strcpy. Instead, we should use wchar_t * wcscpy (wchar_t * wDest, wchar_t wSource); function, the operation is as follows:
Wchar_t s [20];
CString str = "hello ";
Wcscpy (s, (LPCTSTR) str); // It is not converted to UNICODE encoding before, so forced conversion is required here
2. To search for a substring in a string in VC, you only need to perform the following operations:
CString str = "you are a good student ";
Str. Find ("student ");
This cannot be done in EVC, because the Chinese string is UNICODE encoded, we must make the following changes in the search function parameters:
Str. Find (_ T ("student "));

The above are some of the accumulation of operations on Chinese strings when I use EVC to write an application. I will write it in text for future use.

It is estimated that a single-byte swap program will be used later.

Void MyWideCharToMultiByte (WCHAR * wchars, CHAR * schars, int scharsLen)
{
Memset (schars, 0, scharsLen );
CString m_snd = wchars;
Int len = m_snd.GetLength ();
CString tmpstr (m_snd); // copy the string to be sent
Int multibytelen = WideCharToMultiByte (// calculate the number of bytes required after Unicode conversion to Ansi
CP_ACP, // convert according to ANSI code page
WC_COMPOSITECHECK | WC_DEFAULTCHAR, // The default character is used for conversion errors
(LPCWSTR) tmpstr. GetBuffer (len), // string address to be converted
Len, // number of conversions
0, // address of the converted string
0, // The maximum number of characters to convert. If it is 0, the number of bytes required for Unicode conversion is returned.
0, // default character: "\ 0"
0 // default settings
);
WideCharToMultiByte (// convert Unicode to Ansi
CP_ACP,
WC_COMPOSITECHECK | wc_defachar char,
(LPCWSTR) tmpstr. GetBuffer (len ),
Len,
(Char *) schars, // converts to a buffer
ScharsLen, // maximum number of bytes
0,
0
);
}
// The string received by the program is finally saved to CString tmpstr.
// Receives the function snippet
Void MyMultiByteToWideChar (char * schars, CString & wstr)
{
// TODO: Add your specialized code here and/or call the base class
// Char * p = "abcdefg who I am hijk ";
Int widecharlen = MultiByteToWideChar (// calculate the number of bytes required after conversion from Ansi to Unicode
CP_ACP,
MB_COMPOSITE,
(Char *) schars, // Ansi string to be converted
-1, // automatically calculates the length
0,
0
);
CString tmpstr;
Tmpstr. GetBuffer (widecharlen); // allocate memory for saving Unicode strings after conversion
MultiByteToWideChar (// convert from Ansi to Unicode
CP_ACP,
MB_COMPOSITE,
(Char *) schars,
-1,
(LPWSTR) tmpstr. GetBuffer (widecharlen), // convert to tmpstr
Widecharlen // conversion of up to widecharlen Unicode characters
);
Wstr = tmpstr;
}

Void TestFunction ()
{
TCHAR abc [] = _ T ("AB our family AB ");
Char B [15];
MyWideCharToMultiByte (abc, B, sizeof (B ));
// Char c [] = "AB, if it's cd! Abcdefg ";
CString str;
MyMultiByteToWideChar (B, str );

MyWideCharToMultiByte (LPWSTR) str. GetBuffer (0), B, sizeof (B ));
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.