(Zz) Comparison and Application of cstring and string classes

Source: Internet
Author: User

Recently, I am working on a C program in Linux, which requires frequent use of char * string operations, that is, the string provided by C language. the standard string operation API in H operates on characters, and the workload is very heavy. I miss the string template class of STL when I used C ++ as a project. Of course, if you are developing a project that supports MFC on Windows, you can also use the cstring In the MFC class library. Of course there will be no Microsoft MFC class library on Linux, so we can only use the string class of Standard C ++ (that is, the string class in STL ).

The following is a comparison between the cstring class and the string class:

Similarities:

(1) both of them can replace char.

(2) They all encapsulate a variety of string operation interfaces.

(3) They are all c ++ class libraries. --- You may say this is not clear, right, but remember it when using it. Taking the use of string as an example, the following usage is not allowed:

String * pstr = NULL; // defines a pointer to a string.

Pstr-> append ("Hello world."); // bond another character at the end of the string.

In this way, the compiler will not have any warnings or errors, but there will be exceptions during running. Why?

The reason is that we do not understand that string is a class, but we need to call its constructor when defining the class object. No string constructor is called, and the pointer is assigned null. It is obvious that an error occurs when the interface of the object of this class is called. But the compiler cannot find this problem.

The correct method is as follows:

/* Here, the macro new of C ++ must be used instead of malloc in C, because new not only allocates a piece of memory ,*/
/* Also executes the class constructor. Of course, the instantiation of the string class can also be performed through an existing String object. For more information, see */

String * pstr = new string ("Hello world .");
Pstr-> append ("Hello world .");
Cout <"string * pstr is:" <* pstr <Endl;

Or you do not need a pointer. You can do the following:

String STR; // The default constructor is automatically called to construct a string class object.

Str. apend ("Hello world .");

Cout <"string STR is:" <STR <Endl;

(4) They all use the template technology.

Differences:

(1) The cstring class is a class in the MFC provided by Microsoft Visual C ++, so it can be used only for projects that support MFC. For example, in Linux, the project cannot use cstring, and only the string class in Standard C ++ can be used. In addition, because the string class is in the C ++ standard library, it is encapsulated in the STD namespace. before using it, you must declare using namespace STD; the cstring class is not in the STD namespace, because it is not a standard library of C ++, but an encapsulation library of Microsoft. In this case, the string class is used.ProgramBetter portability.

(2) The string class is both a standard C ++ class library and a class library in STL (standard template library). Therefore, it supports iterator operations.

(3) The methods and interfaces provided by the cstring class and the string class are not exactly the same, so don't be confused about how there are no methods in another class in a class. :-)..

(4) The conversion methods between them and char * are different. To convert a string type variable to a char * type string, the string class provides the following three methods:

 
ConstChart * c_str ()Const // c_str returns a string ending with \ 0. 
ConstChart * Data ()Const// Data directly returns the string content in an array. Its size is the return value of size (), and it does not end with \ 0 characters
Size_type copy (chart * Buf, size_type N, size_type Pos = 0)Const// Copy the string content to the Buf space.
 
Note:The return type of c_str () is a pointer to the constant chart type, indicating that the content of the Space indicated by the pointer cannot be modified. It can only be read and cannot be changed. Pointer returned by c_str ()
Is the internal pointer of string, and does not copy its content like the copy function. This can be seen in the following example:
 
String * pstr = new string ("Hello world .");

Const char * pTMP = pstr-> c_str (); // no memory is allocated for the pointer pTMP through malloc or new, but the data pointer in the string is assigned to pTMP.
Cout <"Get the string-> CSTR is:" <pTMP <Endl; // the output of Hello world is correct.
 
However, if you use the copy method, you must use the following method:
 
Char * P = (char *) malloc (100 * sizeof (char); // the pointer P must be allocated with memory space to store the data copied from the string.
Pstr-> copy (p, pstr-> length (), 0); // if there is no memory allocated above, this statement will report a segment error during running.
Cout <"char * P: copy from string is:" <p <Endl; // The correct output string Hello World
 
Converting a String object of the cstring type to a char * string is a little complicated. There are also three methods:

I encountered a problem today. I used to convert from tchar * To cstring. Today I need to convert cstring to tchar *. I found the msdn document and didn't find any ready-made functions available. I searched the internet and found many methods. There are several types:

Method 1: use forced conversion. For example:

Cstring thestring ("this is a test ");
Lptstr lpsz = (lptstr) (lpctstr) thestring;

Method 2: Use strcpy. For example:

Cstring thestring ("this is a test ");
Lptstr lpsz = new tchar [thestring. getlength () + 1];
_ Tcscpy (lpsz, thestring );

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

Method 3: Use cstring: getbuffer. For example:

Cstring S (_ T ("this is a test "));
Lptstr P = S. getbuffer ();
// AddCode
If (P! = NULL) * P = _ T ('\ 0 ');
S. releasebuffer ();
// Release immediately after use, so that other cstring member functions can be used.
-------------------------------------------------------------------

I tried both of the following methods to succeed. Finally, I chose the simple second method, because if the third method is used, we need to use getbuffer (); function, the use of this function requires great caution.

The source code is as follows:

/**********
Check whether the entered mobile phone model is valid. The phone model must start with coolpad. If the value is valid, true is returned. Otherwise, false is returned.
***********/
Bool cautobuildconfigdlg: check1_ename (cstring str1_ename)
{
Wchar_t * pdest;
Cstring strmobilename_temp;
Strmobilename_temp = strmobilename;
Tchar strcoolpad [] = l "coolpad _";

Lptstr lpsz = new tchar [strmobilename_temp.getlength () + 1];
Wcsncpy_s (lpsz, (strmobilename_temp.getlength () + 1), strmobilename_temp, (strmobilename_temp.getlength () + 1 ));

Errno_t err;
Err = _ wcsupr_s (lpsz, strmobilename_temp.getlength () + 1); // because no case-insensitive search substring function is found, it is decided to convert to uppercase and then compare.
Pdest = wcsstr (lpsz, strcoolpad );

If (pdest! = NULL)
{
Return true;
}
Else
{
Return false;
}
}

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.