Cstring, wchar, and char Conversion

Source: Internet
Author: User

1. Define the macro in the header file;
# Define Unicode
# DEFINE _ Unicode

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 to a data buffer, a valid string in the buffer (which is inaccessible and is a hidden area located 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.

 

 

 

 

######################################## ###############################

1. Convert cstring to wchar_t

Cstring Path = "ASDF ";

Wchar_t wstr [1, 256] = path. allocsysstring ();

Or:

Wchar_t wcstring [256];

Multibytetowidechar (cp_acp, 0, path,-1, wcstring, 256 );

2. Convert wchar_t to cstring

Widechartomultibyte (cp_acp, 0, wcstring, 256, path. getbuffer (0), 256, null, null );

Path. releasebuffer (0 );

3. Convert string to cstring

Cstring. Format ("% s", String. c_str ());

4. Convert Char to cstring

Cstring. Format ("% s", char *);

5. Convert Char to string

String S (char *);

6. Convert string to char *

Char * P = string. c_str ();

7. Convert cstring to string

String S (cstring. getbuffer ());

Cstring STR = "fdjfdas ";
String S = (lpctstr) STR;

1, string-> cstring
Cstring. Format ("% s", String. c_str ());
C_str () is indeed better than data.
2, char-> string
String S (char *);
You can only initialize it. It is best to use assign () unless it is initialized ().
3, cstring-> string
String S (cstring. getbuffer ());
Releasebuffer () is required after getbuffer (). Otherwise, no space occupied by the buffer is released.

As mentioned in C ++ standard function library
There are three functions that can convert the content of a string to a character array and a C-string
1. Data (), returns a string array without "/0"
2, c_str (), returns a string array with "/0"
3, copy ()

---------------------------------------------------------------

Conversion between cstring, Int, char *, and char [100 --

Conversion between cstring, Int, char *, and char [100 --

Cstring mutual int Conversion

Converts a character to an integer. You can use atoi, _ atoi64, or atol.
To convert a number to a cstring variable, you can use the format function of cstring. For example
Cstring S;
Int I = 64;
S. Format ("% d", I)
The format function is very powerful and worth your research.

Void cstrdlg: onbutton1 ()
{
// Todo: add your control notification handler code here
Cstring Ss = "1212.12 ";
Int temp = atoi (char *) lpctstr (SS ));

Cstring AA;
AA. Format ("% d", temp );
Afxmessagebox ("Var is" + AA );
}

Sart. Format ("% s", Buf );

Convert cstring to char *

/// Char * To cstring
Cstring strtest;
Char * charpoint;
Charpoint = "give string a value ";
Strtest = charpoint;

/// Cstring to char *
Charpoint = strtest. getbuffer (strtest. getlength ());

There is no string in Standard C, char * = char [] = string

Char * To cstring

You can use the cstring. Format ("% s", char *) method to convert char * To cstring.

Convert cstring to char *

Use the operator (lpcstr) strtest or (char *) (lpcstr) strtest.

Cstring conversion char [100]

Char A [100];
Cstring STR ("aaaaaa ");
Strncpy (A, (lpctstr) STR, sizeof ());

 

(1) Overview

String and cstring are both string template classes. string is a string class defined by the standard template class (STL) and has been incorporated into the C ++ standard;

Cstring (typedef cstringt> cstring) is the most common string class in Visual C ++. It inherits from the csimplestringt class and is mainly used in MFC and ATL programming, the main data types include char (used in ANSI), wchar_t (UNICODE), and tchar (both ANSI and Unicode );

Char * is the most commonly used string pointer in C programming. It generally ends with '/0;

(2) Construction

String is convenient and can be constructed from almost all strings, including cstring and char *;

Followed by cstring, which can be constructed from some basic string variables, including char;

Char * has no constructor and can only be assigned a value;

Example:

Char * psz = "joise ";

Cstring CSTR (psz );

String STR (CSTR );

(3) Operator Overloading

A) operator =

String is the most convenient, and almost all strings can be assigned directly, including cstring and char *;

Followed by cstring. You can directly assign values using some basic strings, including char;

Char * can only be assigned values by pointers, which is extremely dangerous. We recommend that you use strcpy or memcpy. In addition, if the initial value is not assigned to char *, we recommend that you set it to null first, to avoid wild pointers and drive you crazy;

Example:

Char * psz = NULL;

Psz = new char [10]; // Of course, the above is directly written as char * psz = new char [10 ];

Memset (psz, 0, 10 );

Strcpy (psz, "joise ");

Cstring CSTR;

CSTR = psz;

String STR;

STR = psz;

STR = CSTR;

Delete [] psz;

B) operator +

String is similar to cstring. It can be added directly to char *, but the + operator cannot be used with each other. That is, string STR = STR + CSTR is invalid and must be converted to char *;

Char * has no + operation. Only two pointers can be connected using strcat;

Example:

Char * psz = "joise ";

Cstring CSTR = psz;

CSTR = CSTR + psz;

String STR = psz;

STR = STR + psz;

Strcat (psz, psz );

Strcat (psz, CSTR); // valid

Strcat (psz, STR); // invalid. Therefore, cstring can be automatically converted to const char *, but string cannot.

C) operator ++ =

String is the most powerful and can be used with almost all string variables + =, including cstring and char *;

Followed by cstring, which can be + = with some basic string variables, including char;

Char * has no + = Operator and can only use strcat to connect two pointers;

D) operator []

The cstring is the best. When a cross-border request is made, an asserted exception is thrown;

The results of the out-of-bounds string and char * subscripts are undefined;

Example:

Char * psz = "joise ";

Cstring CSTR = psz;

Cout <CSTR [8];

String STR = psz;

Cout <STR [8];

Cout <psz [8];

E) operator =, Operator! =, Operator>, operator <, operator> =, perator <=

Cstring and string cannot be compared, but both can be compared with char * and compared with the value rather than the address;

Cout <(psz = CSTR );

Cout <(psz = Str );

Cout <(STR = psz );

Cout <(CSTR = psz); // The code above returns 1

(4) common algorithms

A) Search

Char * string cstring
Find the specified strchr
Strstr
Strrstr
Strspfind find
The first matched value fild_first_of findoneof starts from the end to find reservefind. The specified matching method is find_if.
Note: In find_if, values in the range are substituted into the matching function one by one until true is returned.

B) Comparison

Function char * string cstring to find the specified value (case sensitive) strcmp
Strncmp
Strcoll
_ Strncoll operator <
Operator>
Operator <=
Operator> =
Operator =
Operator! = Collate

Compare searches for the specified value (Case Insensitive) _ stricmp
_ Strnicmp
_ Stricoll
_ Strnicoll collatenocase

Comparenocas
Note: If the return value is <0, the previous value is smaller than the subsequent value, and vice versa.

C) replace

Function char * string cstring to find the specified value _ strset
_ Strnset
Replace
Replace_copy
Replace_copy_if
Replace_if replace
D) insert

Function char * string cstring to find the specified value insert

E) added the dynamic added value of char * string cstring strcat push.

Append append

Appendchar

Appendformat

F) intercept

Function char * string cstring get part value substr left

Mid

Right

Truncate

G) Remove

Function char * string cstring remove part of the value remove Blank Value removeblks

Note: This is provided by ATL. Non-C function remove_if trim

Trimleft

Trimrig

H) case-insensitive Conversion

Function: Convert char * string cstring to uppercase/lowercase _ strlwr

_ Strupr makelower

Makeupper

I) conversion from other types

Convert char * string cstring to a number atoi

Atod

Convert atof format to char * c_str
Getbuffer

Getbuffersetlen
J) Format

Function char * string cstring formatting sprintf format

K) Get the length

Char * string cstring
Get strlen length getlength get size getalloclength
L) null judgment

Function char * string cstring determines whether it is null to determine whether = NULL or whether the first character is '/0' empty isempty
M) redefinition size

Function char * string cstring redefinition realloc
New resize getbuffersetlength
N) release resources

Function char * string cstring releases free

Delete (Delete []) releasebuffer

Releasebuffersetlength

(5) Security>

Cstring> string> char *;

(6) Flexibility

Cstring> string> char *;

(7) portability

Char * = string> cstring

*****************

Char to cstring is equal!

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.