Summary of C++string class

Source: Internet
Author: User

First, the initialization of a string

First, in order to use the string type in your program, you must include the header file <string>. As follows:

   #include <string>

Note that this is not string.h,string.h is a C string header file.

The string class is a template class that is located in the namespace STD, and is typically added for ease of use:

   using namespace std;

Declaring a string variable is simple:

string str;

Test code:

#include <iostream> #include <string>using namespace Std;int main () {string str;  Defines an empty string strstr = "Hello World";   Assign a value of "Hello World" char cstr[] = "ABCDE" to str;  Defines a C string S1 (str);       Call the copy constructor to generate a replica of s1,s1 str cout<<s1<<endl;string s2 (str,6);     In Str, the part starting at position 6 is regarded as the initial value of S2 cout<<s2<<endl;string S3 (str,6,3);  The portion of STR, starting at 6 and at most 3 of the length, as the initial value of the S3        Cout<<s3<<endl;string S4 (CStr);   The C string is used as the initial value of the S4 cout<<s4<<endl;string S5 (cstr,3);  S5 The first 3 characters of the C string as the initial value of the string. Cout<<s5<<endl;string S6 (5, ' A ');  Generates a string containing 5 ' a ' characters cout<<s6<<endl;string S7 (Str.begin (), Str.begin () +5); The characters within the interval Str.begin () and Str.begin () +5 are the initial values Cout<<s7<<endl;return 0;}

The results of the program execution are:

Hello World

World

Wor

Abcde

Abc

AAAAA

Hello

Second, string comparison and other operations

You can compare strings with = =, >, <, >=, <=, and! =, you can concatenate two strings with the + or + = operator, and you can use [] to get a specific character.

#include <iostream> #include <string>using namespace Std;int main () {string str;cout << "please input Your name: "<<endl;cin >> str;if (str = =" Li ")   //String equality comparison cout <<" You are li! " <<endl;else if (str! = "Wang")  //String Unequal comparison cout << "You is not wang!" <<endl;else if (str < "Li")     //string less than compare,>, >=, <= similar cout << "Your name should be ahead of Li" <& Lt;endl;elsecout << "Your name should be after of Li" <<endl;str + = ", welcome!";  String +=cout << str<<endl;for (int i = 0; i < str.size (); i + +) cout<<str[i];  Like an array, get a specific character by [] return 0;}

The results of the program execution are:

Please input your name:

Zhang

You is not wang!

Zhang, welcome!

Zhang, welcome!

In the above example, " cout<< str[i"; "Can be changed to: cout<< str.at (i);

Iii. Description of String properties

The following functions can be used to obtain some features of string:

int Capacity ()const;    // returns the current capacity (that is, the number of elements in a string that do not have to increase memory)
int max_size ()const;    // returns the length of the largest string that can be stored in a string object
int size ()const;        // returns the size of the current string
int Length ()const;       // returns the length of the current string
bool Empty ()const;        // whether the current string is empty
void Resize (int len,char c);  // set the current size of the string to Len, much less to fill, more out of the character C is filled with insufficient parts

Test code:

#include <iostream> #include <string>using namespace Std;int main () {string str;    if (Str.empty ())    cout<< "str is NULL." <<endl;    else    cout<< "STR is not NULL." <<ENDL;STR = str + "ABCDEFG";cout<< "str is" <<str<<endl;    cout<< "str s size is" <<str.size () <<endl;     cout<< "str s capacity is" <<str.capacity () <<endl; cout<< "Str ' s max size is" <<str.max_size () <<endl;cout<< "Str ' s length is" <<str.length () <<endl;str.resize (' C ');cout<< "str is" <<str<<endl;str.resize (5);cout<< "STR is" <<str<<endl;return 0;}

The results of the program execution are:

STR is NULL.

STR is ABCDEFG

Str ' s size is 7

Str ' s capacity is 15

Str ' s max size is 4294967294

Str ' s length is 7

STR is ABCDEFGCCC

STR is ABCDE

Iv. Finding a string

Because lookups are one of the most frequently used features, String provides a very rich look-up function: (Note: string::npos)

Const basic_string &str, size_type index);  // returns the position of the first occurrence of STR in the string (from index) and returns if not found String::npos
Const Char *str, size_type index);  // Ibid .
Const Char *str, size_type index, size_type length);  // returns the position of the first occurrence of STR in the string (from index, length) and returns String::npos if not found
char ch, size_type index);  // returns the position of the first occurrence of the character ch in the string (from index), and returns if not found String::npos

Note: Find if string A contains substring B, not with Stra.find (StrB) > 0 but stra.find (strB)! = String:npos What is this for? (a mistake that beginners tend to make) This section is referenced from web100 and luhao1993

First look at the following code

 int  idx = str.find ( " abc  "   if  (idx = = string :: NPOs); 

In the above code, the type of IDX is defined as int, which is wrong, even if the definition is unsigned int is also wrong, it must be defined as String::size_type. npos This is defined as:   static const size_ Type NPOs =-1 ; Because String::size_type (defined by the string configurator allocator) describes size, it needs to be an unsigned integer type. Because the default Configurator takes type size_t as Size_type, 1 is converted to an unsigned integer type, and NPOs is the largest unsigned value of that type. However, the actual value depends on the actual definition of the type Size_type. Unfortunately, these maximum values are not the same. In fact, (unsigned long)-1 and (unsigned short)-1 are different (provided the two types differ in size). Therefore, the comparative idx = = String::npos, if the value of IDX is-1, because the IDX and the string String::npos type are different, the comparison result may be false. SoThe best way to determine whether the results of find functions such as find () is NPOs is to compare directly.

Test code:

Operation Result:

V. Other common functions

string &insert (int p,conststring &s);  // Insert string S at p position
string &replace (intint N,constchar//  Delete n characters starting with p and insert string s at p
string &erase (intint n);  // remove n characters from p to return the modified string
string substr (int0,intconst;  // returns a string of n characters starting at Pos
void Swap (string &s2);    // swap the current string with the value of S2
string &append (constchar *s);   // concatenate the string s to the end of the current string
void push_back (char c)   // current string trailing plus one character C
Const Char *data ()const;   // returns a non-null-terminated C-character array,data (): Similar to C_str () , used for string-to-const char* where it returns an array that is not terminated with a null character,
Const Char *c_str ()const;  // returns a null-terminated C string, the C_STR () function returns a pointer to a regular C string, the same as this string string, for string to const char*

Test code:

#include <iostream> #include <string>using namespace Std;int main () {string str1 = "ABC123DEFG"; string str2 = " Swap! "; Cout<<str1<<endl;cout<<str1.erase (3,3) <<endl;  3 characters starting at index 3, i.e. deleted "123" Cout<<str1.insert (0, "123") <<endl; Insert Cout<<str1.append in head ("123") <<endl;   The append () method can add A string str1.push_back (' A ');  The Push_back () method can only add a single character cout<<str1<<endl;cout<<str1.replace (0,3, "Hello") <<endl; 3 characters starting at index 0 are replaced with "Hello" cout<<str1.substr (5,7) <<endl; Starting from index 5 7 bytes Str1.swap (str2), cout<<str1<<endl;const char* p = str.c_str ();p rintf ("%s\n", p); return 0;}

The results of the program execution are:

Abc123defg

Abcdefg

123abcdefg

123abcdefg123

123abcdefg123a

helloabcdefg123a

Abcdefg

swap!

swap!

Summary of C++string class

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.