Use of strings in C + +

Source: Internet
Author: User
When we start using the C language to handle strings, we get a lot of trouble. The C language lacks the corresponding string handler function, and if you want to implement a string function, we can do it by ourselves. But when it comes to C + +, the processing of strings becomes surprisingly simple. Today, let's learn about the highest-frequency string-handling functions in C + +. The sample code is uploaded to: https://github.com/chenyufeng1991/CppString.

The first step is to introduce a string header file in C + +:

#include <string>


Please note that the header file here is not. h, otherwise it becomes the header file in C language.

(1) Creating a string


There are several ways to create a string, and the most typical way is to use a copy constructor.

String str ("Chenyufeng", 3);  cout << str << Endl;

cout copies the most recent 3-character string at the beginning of the original string. The result of the printing is Che.

String str2 ("Chenyufeng", 2,3);  cout << str2 << Endl;


cout copies the most recent 3-character string at the beginning of the original string index=2. The print result is eny.

=: string Assignment  str2 = "Robert";  cout << str2 << Endl;


It is also possible to assign a value string to a variable in the form of a direct assignment, using "=". Print the result to Robert.


(2) Swap: Swap the value of two strings

Swap: Swap the value of two strings string    string1 = "Chen";     String string2 = "Yufeng";     Swap (string1, string2);     cout << "string1 =" << string1 << "string2 =" << string2 << Endl;


The printed result is already swapped with the value of the original string.


(3) +,append: Adding a string

+ =, append: Adds string     stringorigin = "Chen" at the tail      ; String stringappend = "Yufeng";      Stringorigin = Stringorigin + stringappend;      cout << "Stringorigin =" << stringorigin << Endl;        Stringorigin.append ("_ok");      cout << "stringoriginappend =" << stringorigin << Endl;


Note that adding a string operation modifies the original string. It is convenient to add the string directly using the + sign.


(4) Insert: Inserts a string at the specified position

Insert: Inserts string    stringinsertorigin = "Chenyufeng" in the specified position;      Stringinsertorigin.insert (3, "__");      cout << "Stringinsertorigin =" << stringinsertorigin << Endl;


The above code can be inserted in the indx=3 position __ underline, the printing result is Che__nyufeng.


(5) Erase,clear Delete string

Erase: Delete character   string stringeraseorigin = "Chenyufeng";     Stringeraseorigin.erase ();     cout << "Stringeraseorigin =" << stringeraseorigin << Endl;         Clear: Remove all characters    string stringclearorigin = "Chenyufeng";     Stringclearorigin.clear ();     cout << "Stringclearorigin =" << stringclearorigin << Endl;


In fact, all of this is to empty the string.


(6) Replace: replace string

Replace: Replaces a string with a size character at the beginning of a POS position replaced by the string     Stringreplaceorigin = "Chenyufeng";      Stringreplaceorigin.replace (3, 2, "the");      cout << "Stringreplaceorigin =" << stringreplaceorigin << Endl;


The code above replaces the string 2 characters starting with index=3 with "66" and prints the result as Che66ufeng.


(7) = =,, =: Compare string size


Using this operator to manipulate strings in C + + is in fact an operator overload. The string comparison size is based on the dictionary order of the alphabet, or the ASCII value in sequential comparison of the size. Until a different letter of two strings is compared or the last stop of a string is compared.

==,<,>,<=,>=: Comparing strings string    stringleft = "Zhen";     String stringright = "Yufeng";     if (Stringleft = = stringright)     {         cout << "equal" << Endl;     }       if (stringleft! = stringright)     {         cout << "Not Equal" << Endl;     }       if (Stringleft < stringright)     {         cout << "Stringleft < stringright" << Endl;     }       if (Stringleft > Stringright)     {         cout << "Stringleft > Stringright" << endl;     }


(8) Size,length: Calculating string Lengths


The length of the computed string here is different from the C language, not including the end, and calculates the true length.

Size (), Length (): Calculates the string length string     stringcount = "Chenyufeng";      cout << "stringsize =" << stringcount.size () << Endl;      cout << "stringlength =" << stringcount.length () << Endl;


The above print results are all 10.


(9) Empty: Determine if the string is empty

Empty (): Determines whether the string is empty string    stringisempty = "";      String stringnotempty = "Chen";      if (Stringisempty.empty ())      {          cout << "stringisempty = = Empty" << Endl;      }      else      {          cout << "Stringisempty! = Empty" << Endl;      }        if (Stringnotempty.empty ())      {          cout << "stringnotempty = = Empty" << Endl;      }      else      {          cout << "Stringnotempty! = Empty" << Endl;      }


(10) input and output stream of string

Input output stream    cout << "Please enter a string" <<endl;      string Stringinput;      Cin >> Stringinput;      cout << "stringinput =" << stringinput << Endl;


A string can also use an input-output stream similar to other C + + data types. You can use the ENTER key to end the input stream.


(one) Max_size: The maximum number of strings that can be accommodated.

Max_size:    string stringmaxsize;      cout << "stringmaxsize =" << stringmaxsize.max_size () << Endl;


The result is: 18446744073709551599. Indicates that the string can hold so many characters.


[], at: element access and modification

[],at (): element access    string Stringat = "Chenyufeng";      cout << "stringat[3] =" <<stringat[3 "<< Endl;      cout << "stringat.at (3) =" << stringat.at (3) << Endl;        STRINGAT[3] = ' 6 ';      stringat.at (5) = ' 9 ';      cout << "Stringat =" << stringat << Endl;


Strings can be manipulated as well as arrays, accessed using subscripts, and can be modified with the original string.


Compare: string comparison, return 0,1,-1.

Compare ()     string stringcompare = "Chenyufeng";      int AAA = Stringcompare.compare ("Chen"); > 0      int bbb = Stringcompare.compare ("Chenyufeng");//= = 0      int CCC = Stringcompare.compare ("Done");//< 0      cout << "AAA =" << aaa << "; bbb =" << bbb << "; CCC =" << CCC << Endl;


(+) Substr: Take substring

substr     String stringsubstr = "Chenyufeng";     3 characters starting from index 4     cout << "Stringsubstr.substr (4,3) =" << stringsubstr.substr (4,3) << Endl;       All characters starting from index 4    cout << "Stringsubstr.substr (4) =" <<stringsubstr.substr (4) << Endl;       The entire character    cout << "stringsubstr.substr () =" <<stringsubstr.substr () << Endl;


() find: Find a character

Find     string stringfind = "Chenyufeng";      Stringfind.find (' n ');      cout << "Stringfind.find (' n ') =" << stringfind.find (' n ') << Endl;        cout << "stringfind.find_first_of (' e ') =" << stringfind.find_first_of (' e ') << Endl;            cout << "stringfind.find_last_of (' e ') =" << stringfind.find_last_of (' e ') << Endl;

The default find function is the subscript index that returns the first occurrence of a character. Find_first_of and Find_last_of are the first and last occurrences of the index of a character.

The above is the use of strings in C + + content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.