C++ Standard template library string class introduction and usage

  • 2020-06-12 10:14:26
  • OfStack

introduce

c++ string string object belongs to a class, built-in a lot of practical member functions, simple operation, convenient and more intuitive.

The namespace is std and belongs to the header file < string > Note: No < string.h > .

The follow up code shows that string is actually just one typedef of the basic_string template class.

The assignment


 // methods 1
 string str1 = "woniu201";
 // methods 2
 char* p = "woniu201";
 string str2 = p;

traverse


 // methods 1  Use subscript 
 for (int i=0; i<str1.length(); i++)
 {
 printf("%c", str1[i]);
 }
 // methods 2  Using iterators 
 string::iterator it;
 for (it=str1.begin(); it!=str1.end(); it++)
 {
 printf("%c", *it);
 }

To find the


 string str5 = "woniu201";
 int pos1 = str5.find("n", 0);   // From the position 0 Start looking for characters n In a string str5 The position of 
 int pos2 = str5.find("niu", 0);  // From the position 0 Start looking for strings niu In a string str5 The position of 
 int pos3 = str5.find("niu", 0, 2);// From the position 0 Start looking for strings niu The first two characters form a string in str5 The position of 

The interception


 string str3 = "woniu201";
 string str4 = str3.substr(0,5);// Returns from the subscript 0 The start of the 5 A string of two characters  

other


 // String concatenation 
 string str6 = "woniu201";
 string str7 = "hailuo201";
 string str8 = str6 + str7;
 // Judge whether it is equal 
 bool bRet1 = (str6 == str7); // Is equal to true , or for false
 // Determines whether the string is empty 
 bool bRet2 = str6.empty();
 // String insertion 
 string str9 = str6.insert(0, str7); // string str6 the 0 Position insert string str7
 // String swapping 
 str6.swap(str7);
  // Determine whether it contains 
  string::size_type idx = str6.find("woniu");
  if(idx == string::npos)
  {
    cout << "not found" << endl;
  }

conclusion


Related articles: