Usage and example of C + + string __c++

Source: Internet
Author: User
Tags alphabetic character strcmp
Use occasion:

String is an important part of the C + + standard library, primarily for string processing. You can use the input/output stream to operate directly, or through files and other means. The C + + algorithm library also has good support for string, and there is a good interface between string and C-language strings. Although there are some drawbacks, but afterward.
Most of the code used is from the CPP official website, because the example is very complete. declaring and Initializing methods:

To use string, first add < string > in header file
The Declaration method is also very simple to declare:

String s;//declares a string object
string ss[10];//declares an array of a string object
Initialize:

Initialization with an equal sign is called copy initialization, and initialization without an equal sign is called direct initialization.

#include <bits/stdc++.h>
using namespace std;

int main ()
{
    Ios::sync_with_stdio (false);
    String s;//default initialization, an empty string string
    S1 ("SSSs"),//s1 is a replica string ssss (s2) of the literal "S1", and//s2
    is a copy of the S1 string
    s3=s2;// S3 is a copy of the S2
    string S4 ("C");//The S4 initializes
    string s5= "Hiya";//Copy initializes
    string s6=string (A. ' C '); Generates an initialized object that is copied to

    the S6//string s (cp,n)
    char cs[]= "12345";
    String S7 (cs,3);//Copy the first 3 characters of the string CS into S

    //string s (s2,pos2)
    string s8= "ASaC";
    String S9 (s8,2);//Copy from the second character of the S2, not exceeding S2 size

    //string s (s2,pos2,len2)
    string s10= "Qweqweqweq";
    String S11 (s10,3,4);//S4 is S3 a copy of 4 characters starting with subscript 3, more than s3.size appears undefined return
    0;
}
string Processing: substr Action:

Note that SUBSTR does not have an iterator as a parameter

#include <bits/stdc++.h>
using namespace std;
int main ()
{
    Ios::sync_with_stdio (false);
    String s= "ABCDEFG";

    The S.SUBSTR (pos1,n) returns a string string S2=s.substr (1,5) of the n characters followed by pos1,
    //bcdef

    //s.substr (POS)/Get a POS to the end of the string
    string S3=s.substr (4);//EFG return

    0;
}

If the position entered exceeds the length of the character, a Out_of_range exception insert Operation is thrown:

Code from the CPP official website, after their own collation
Note Using iterators when parameters differ from unsigned numbers

#include <bits/stdc++.h> using namespace std;
    int main () {Ios::sync_with_stdio (false);
    String str= "to be question";
    String str2= "the";
    String str3= "or not to be";

    String::iterator it;                 S.insert (POS,STR)//Inserts STR Str.insert (6,STR2) at the POS position of S;             To being the question//s.insert (pos,str,a,n) inserts the N-character Str.insert (6,str3,3,4) at the POS position in Str at the point of insertion of a to the back;    To the question//s.insert (pos,cstr,n)//Inserts the CStr string at the POS position from the beginning to the back of the N-character Str.insert (8);            To being is the question//s.insert (POS,CSTR) inserts the CStr Str.insert at the POS position of S ("to be");               To being is the question//s.insert (pos,n,ch) inserts n ch str.insert above S.pos position (15,1, ': '); To the question//s.insert (s.it,ch) inserts a character ch ahead of S's it point position, returns the iterator for the newly inserted position of the be:that it = Str.insert (str . Begin () +5, ', ');
    To being, not to Be:that is the question//s.insert (S.IT,N,CH)//inserts n ch in front of s where it pointsStr.insert (Str.end (), 3, '. ');  To being, not to be:that is the question ...//s.insert (IT,STR.ITA,STR.ITB) inserts a string of [ITA,ITB) before the location it points to Str.insert (It+2,str3.begin (), Str3.begin () +3);
To being, or not to be:that are the question. return 0;
 }
Erase action:

Used to perform a delete operation
There are three kinds of specified POS and Len, where the POS is the starting position, the POS and the back len-1 string remove the iterator, delete the character iterator range that the iterator points to, delete the range of strings, and open the range left and right

Code from the CPP official website

#include <iostream>
#include <string>

int main ()
{
  std::string str example sentence. ");
  Std::cout << str << ' \ n ';
                          "This is a example sentence."
  Str.erase (10,8);            ^^ ^^ ^^ ^^
  //directly specify the position of the deleted string 8 characters after the tenth
  std::cout << str << ' \ n ';
                            "This is a sentence."
  Str.erase (Str.begin () +9);/           ^
  //Delete iterator-pointing character
  std::cout << str << ' \ n ';
                            "This is a sentence."       ^^ ^^ ^
  str.erase (Str.begin () +5, Str.end () -9);
  Remove the iterator range character
  std::cout << str << ' \ n ';
                            "This sentence."
  return 0;
}
Append and replace operations:

The Append function can be used to append characters and strings at the end of a string. Because the string overloads the operators, you can also use the + = operation to implement the
Repalce, as the name suggests, is the meaning of substitution, delete first, then increase.
Code from the CPP official website, with its own explanation

#include <iostream>
#include <string>

int main ()
{
    std::string str;
    std::string str2= "writing";
    std::string str3= "Print and then 5 more";

    Append directly to a str2 string
    str.append (str2);                       "Writing"
    //STR3 3 string
    str.append (str3,6,3) appended to the beginning of the 6th character;                   "Ten"
    //Append the first 5 characters of the string parameter
    str.append ("dots are cool", 5);          "Dots"
    //directly add
    str.append ("here:");                   "Here:"
    //Add 10 '. '
    Str.append (10u, '. ');                    "...."
    //Add STR3 iterator range string
    str.append (Str3.begin () +8,str3.end ());  "And then 5 more"
    //finally this is more special, meaning to add 5 ' a ', in fact, the 65 corresponding ASC code inside the parameter is the
    str.append<int> (5,65);                "..."
    //String append can also be implemented with overloaded operator
    str+= "Lalala";
    Std::cout << str << ' \ n ';
    return 0;
}

Use of Replace, replace supports using unsigned integers to find locations, and supports finding locations with iterators

#include <iostream> #include <string> int main () {std::string base= "This is a test string."
    std::string str2= "n Example";
    std::string str3= "Sample phrase";

    std::string str4= "useful." Replace signatures used in the same order as described above://Using positions:0123456789*12345           6789*12345 std::string str=base;
    "This is a test string."          The 9th character and the following 4 characters are str2 instead of str.replace (9,5,STR2); "This is a example string."     (1)//the 19th string and the following 5 characters are substituted for str.replace (19,6,str3,7,6) with the 7th character of STR and the following 5 characters; "This is a example phrase."     (2)//8th character and the following 9 characters replace Str.replace (8,10, "just a") with string arguments;     "This is just a phrase."  (3)//8th character and the following 5 characters replace Str.replace with the first 7 characters of the string argument (8,6, "A Shorty", 7);    "This is a short phrase."        (4)//22nd and the following 0 characters with 3 exclamation mark replace str.replace (22,1,3, '! ');  "This is a short phrase!!!"                      (5)//Iterator principle Ibid.//Using iterators:                         0123456789*123456789* str.replace (Str.begin (), Str.end () -3,STR3);      "Sample phrase!!!"             (1) str.replace (Str.begin (), Str.begin () +6, "Replace");     "Replace phrase!!!"    (3) Str.replace (Str.begin () +8,str.begin () +14, "is coolness", 7);    "Replace is cool!!!"                (4) Str.replace (Str.begin () +12,str.end () -4,4, ' O ');  "Replace is Cooool!!!"    (5) Str.replace (Str.begin () +11,str.end (), Str4.begin (), Str4.end ());//"Replace is useful."   
    (6) Std::cout << str << ' \ n ';
return 0;
 }

The replace operation can be replaced with insert and erase operations, but the replace operation is more convenient.

Assign action:
Assign operations are present in a column container, such as vectors and so on. is a very basic operational function that string uses assign to be able to assign values flexibly.
Code from the CPP official website

#include <iostream> #include <string> int main () {std::string str;

    std::string base= "The quick brown fox jumps over a lazy dog."
    Used in the same order as described above://Direct base assignment to Str str.assign (base);
    Std::cout << str << ' \ n ';
    Assignments the base 10th character and the following 8 characters to the Str str.assign (base,10,9);         Std::cout << str << ' \ n ';
    "Brown Fox"//("Pangrams are Cool", 7) by assigning 0 to 6 strings in parameters to Str str.assign;         Std::cout << str << ' \ n ';
    "Pangram"//Direct use of parameter assignment str.assign ("c-string");         Std::cout << str << ' \ n ';
    "C-string"//to STR assigned 10 ' * ' character str.assign (10, ' * ');         Std::cout << str << ' \ n ';
    "**********"//Assignment is 10 '-' str.assign<int> (10,0x2d);         Std::cout << str << ' \ n ';
    "----------"//Specifies the base iterator range string Str.assign (Base.begin () +16,base.end ()-12);         Std::cout << str << ' \ n '; "Fox Jumps over "return 0;
 }
search operations for string:

The string class provides a number of excellent, easy to use member methods. And there are a lot of practical techniques in generic algorithms. Find and RFind functions:

The Find function is primarily to look for whether a string appears in the called string and is case sensitive.
Code from the CPP official website

#include <bits/stdc++.h> using namespace std;
    int main () {Ios::sync_with_stdio (false);
    std::string Str ("There are two needles in this haystack with needles");

    std::string str2 ("needle"); Different member versions of the same order as above://To find the first occurrence of the needle in Str, and to return to the location where it appears, otherwise return to the end Std::siz
    e_t found = Str.find (STR2);
    if (found!=std::string::npos) std::cout << "needle" found at: "<< found << ' \ n ';
    In Str, the first 6 characters found=str.find ("Needles are small", found+1,6) are found starting from the position of found+1;
    if (found!=std::string::npos) std::cout << "Second ' needle ' found at:" << found << ' \ n ';
    Find the string found=str.find ("haystack") in the parameter in STR;
    if (found!=std::string::npos) std::cout << "' haystack ' also found at:" << found << ' \ n ';
    Find a character found=str.find ('. '); if (found!=std::string::npos) std::cout << "Period found at:" << found << ' \ n'; In combination, the STR2 is replaced by a string in the parameter table//Let's replace the "Needle:str.replace" (Str.find (STR2), Str2.length (), "preposition")
    ;
    Std::cout << str << ' \ n ';
return 0;
 }

The RFind function is to find the last occurrence of the matching string, the return position is still from the number of after the.

#include <bits/stdc++.h>
using namespace std;

int main ()
{
    Ios::sync_with_stdio (false);
    std::string Str ("The Sixth sick Sheik ' sixth sheep ' sick.");
    Std::string Key ("sixth");/                    ^
    //rfind is to find the last occurrence of the matching string
    std::size_t found = Str.rfind (key);
    if (Found!=std::string::npos)
    {
        cout<<found<<endl;//output
        str.replace (found, Key.length (), "Seventh"),//found sixth replaced with seventh
    }

    std::cout << str << ' \ n ';
    return 0;
}

Search efficiency is very high, I have not seen the STL source analysis, but the feeling is implemented with KMP. Oh, you can write one yourself. find_....of function: find_first_of (args) finds the first occurrence of any character in args find_last_of (args) the last occurrence of the position find_fist_not_of (args) find the first character that is not in args find_last_not_of find the last character not appearing in args

#include <bits/stdc++.h>
using namespace std;

int main ()
{
    Ios::sync_with_stdio (false);
    std::string str1 ("Please, replace the vowels in this sentence by asterisks.");
    std::size_t found1 = str1.find_first_of ("Aeiou");
    Find all vowels to replace the while
    (Found1!=std::string::npos)
    {
        str1[found1]= ' * ';
        Found1=str1.find_first_of ("Aeiou", found1+1);
    }
    Std::cout << str1 << ' \ n ';

    In STR2 found the first is not the Association of English Letters and spaces characters
    std::string str2 ("Look for non-alphabetic characters ...");
    std::size_t Found2 = str2.find_first_not_of ("abcdefghijklmnopqrstuvwxyz");
    if (Found2!=std::string::npos)
    {
        std::cout << "The" the "" The "" the "" non-alphabetic character is "<< str2[ FOUND2];
        Std::cout << "at position" << found2 << ' \ n ';
    }
    return 0;
}

Find_last_of and find_last_not_of are basically the same as the primary, so no example code is written. comparison and conversion:

Similar to the C-language string comparison function, the STRCMP function supports string comparison operations, as well as functions in Python and C # languages, which support the conversion of numbers and strings. Some features are c++11.
Note Compiler bugs:
In the MinGW compiler, if the version is less than 3.8, although C++11 is supported but there is a bug in it, the conversion of string and array is not supported. You may want to update the MINGW version, or use g++ directly. Compare function:

As with the strcmp function, if two strings are equal, then 0 is returned and the calling object is greater than the parameter returns 1, less than return-1.
Partial comparisons are also supported in the compare, with 6 parameters that can be set.

 #include <bits/stdc++.h> using namespace std;
    int main () {Ios::sync_with_stdio (false);
    String s1= "123", s2= "123";
    Cout<<s1.compare (S2) <<endl;//0 s1= "123", s2= "1234";
    Cout<<s1.compare (S2) <<endl;//-1 s1= "1234", s2= "123";
    Cout<<s1.compare (S2) <<endl;//1 std::string str1 ("Green apple");

    std::string str2 ("Red apple");
    if (Str1.compare (STR2)!= 0) std::cout << str1 << "is not" << str2 << ' \ n ';  The 6th character of the STR1 and the following 4 characters and parameter comparisons if (Str1.compare (6,5, "apple") = = 0) std::cout << "Still," << str1 <<

    "is a apple\n"; if (Str2.compare (Str2.size () -5,5, "apple") = = 0) std::cout << "and" << str2 << "is also a apple\n"
    ; The 6th character of the STR1 and the following 4 characters and the 4th character of the STR2 and the following 4 characters are compared if (str1.compare (6,5,str2,4,5) = = 0) std::cout << "Therefore, Bo
    th are apples\n ";
return 0; }

Because string overloads the operators, it is also convenient to compare them directly with >,<,==. Numeric Conversions:

In the IO section there are examples of numeric and string conversions, using the StringStream function, which is conveniently defined in c++11 with out-of-the-box function calls.

string and numeric conversions
To_string (Val) Convert Val to string
Stoi (S,P,B) Converts the string s from P to a B-binary int
STOL (S,P,B) Long
Stoul (S,P,B) unsigned long
Stoll (S,p,b) Long Long
Stoull (S,P,B)
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.