Detail the C++ string string class

  • 2020-06-15 09:51:37
  • OfStack

C++ string string class

In C, strings are represented as character arrays, but for the application layer, strings are often used, and continuing to use character arrays is inefficient.

So in the C++ standard library, the strings were newly customized through the class string.

Header file: #include < string >

string directly supports string concatenation string directly supports string size comparisons string directly supports substring lookup and extraction string directly supports string insertion and substitution string also has the flexibility of an array of strings and can access each character through the [] overload operator.

Avoid mixing string arrays with string objects, which can cause unexpected problems

For example, assign a value to an string object through an array of strings:


string str;
  char s[]="12345";

  str.reserve(5);

 for(int i=0;i<5;i++)
  str[i]=s[i];

  cout<<"str:"<<str<<endl;
  cout<<"length():"<<str.length()<<endl;

Print run:

[

str:
length():0

]

This is because using the for loop copy only changes the string content of str, not the length length of str.

Common constructors of string classes are:


string Common constructors of classes are :

string str;  // generate 1 Null string 
 
string str ("ABC") // Is equivalent to  str="ABC"<br>
string str ("ABC", strlen) //  will "ABC" endures str In the , Maximum pre-storage strlen bytes 
 
string s("ABC",stridx,strlen) // will "ABC" the stridx location , To start a string , endures str In the . Maximum storage strlen bytes .
 
string s(strlen, 'A') // storage strlen a 'A' to str In the 

Common member functions of string class are:


str1.assign("ABC");        // empty string string , And then set string String as "ABC"
 
str1.length() ;      // Get the length of the string 
 
str1.size();            // Get the number of strings , Is equivalent to length()
 
str1.capacity();         // Get capacity , The capacity contains the current string The number of characters that can be used without increasing memory 
 
str1.resize(10);        // Indicates that the Settings are current string The string size in , If the size is greater than the current string length , With a character \0 To fill in the excess .
str1.resize(10,char c);     // Sets the string size, if larger than the current string length , With a character c To fill in the excess 
 
str1.reserve(10);         // Set up the string The string capacity in , Data will not be populated .
str1.swap(str2);     // replace str1  and  str2  The string 
 
str1.puch_back ('A');   // in str1 At the end of the add 1 a 'A' character , The argument must be in character form 
 
str1.append ("ABC");    // in str1 At the end of the add 1 a "ABC" string , The argument must be a string 
 
str1.insert ("ABC",2);  // in str1 The subscript for 2 The location of the , insert "ABC"
 
str1.erase(2);       // Delete the subscript 2 The location of the , Such as : "ABCD" --> "AB"
 
str1.erase(2,1);    // From the subscript for 2 Location deletion of 1 a , Such as : "ABCD" --> "ABD"
 
str1.clear();      // Delete all 
 
str1.replace(2,4, "ABCD"); // From the subscript for 2 The location of the , replace 4 bytes , for "ABCD"
 
str1.empty();      // Judgment is empty ,  Empty return true

/*assign() : The mutator  , It will refree the allocated string memory  */
str1.assign("HELLO");     //str1="HELLO"
str1.assign("HELLO", 4);    //str1="HELL" , Only keep 4 A character 
str1.assign("HELLO", 2, 3);    //str1="LLO" , From the position 2 start , Only keep 3 A character 
str1.assign(5, 'c');     //str1="CCCCC"    // Assign by character 

const char* c_str();

Returns 1 constant C string, the same as this string string.

Note: when the contents of string are changed or destroyed, the returned string will not be changed, because the returned string is re-routed through new char[].

Referring to the following code, you can see that the returned C string address is completely different from the string address in string:


string* str = new string("ASD"); //str="ASD" 
const char* c = str->c_str(); 

cout<<c<<endl;     // print  : "ASD" 

printf("&c[0]=%p,&str[0]=%p\n",&c[0],&str[0]); 
       // print :c=0x94bf024,&str[0]=0x94bf008

str->append("dd");   //str="ASDdd"   
cout<<c<<endl;    // print  : "ASD" 

delete str;     // Call the destructor  

cout<<c<<endl;    // print  : "ASD"

Invert correlation (located in the header file < algorithm > )


string str("hello");
 
reverse(str.begin(),str.end());
 
cout<< str <<endl;    // Reverses its own string , print olleh

Find relevant:


string str("ABCDEFGABCD");      //11 A character 
int n;<br>
/* Find the returned location successfully , To find the failure , the n Is equal to the -1*/
/*find(): Find a string from scratch */
n= str.find('A');    // To find the "A",n=0;
n= str.find("AB");    // To find the "AB",n=0;
n= str.find("BC",1);   // From the position 1 place , To find the "BC",n=1;
n= str.find("CDEfg",1,3);  // From the position 1 place , To find the "CDEfg" The former 3 A character , Is equivalent to str.find("CDE",1),n=2;
 
/*rfind(): reverse (reverse) To find the , Start at the end , Look ahead */
n= str.rfind("CD");   // From the position 10 Start looking forward ,n=9
n= str.rfind("CD",5);   // From the position 5 Start looking forward ,n=2
n= str.rfind("CDEfg",5,3); // Is equivalent to str.rfind("CDE",5);  , so n=2
 
 
/* find_first_of (): To find the str Contains any of the substrings 1 A character */
n= str.find_first_of("abcDefg");  // Due to the str location 3 is 'D', Is equal to the "abcDefg" the 'D', so n=3
n= str.find_first_of("abcDefg",1,4); // Is equivalent to str. find_first_of ("abcD",1);  so n=3
 
 
/* find_last_of (): At the end of the search ,  Start at the end , Look forward to see if any of the substrings are contained 1 A character */
n= str.find_last_of("abcDefg");  // Due to the str At the end of the position 10 is 'D', so n=10
n= str.find_last_of("abcDefg",5,4); // Is equivalent to str. find_last_of ("abcD",5);  so n=3
 
 
/* find_first_not_of (): Match any substring 1 A character , Returns if a character is not equal str location , All equal return -1*/
n= str.find_last_not_of("ABC"); // Due to the str location 3'D', Not in the substring , so  n=3
n= str.find_last_not_of("aABDC"); // Due to the str location 4 'F', Not in the substring , so  n=4
n= str.find_last_not_of("aBDC"); // Due to the str location 0 'A', Not in the substring , so  n=0
<br>
/* find_last_not_of (): Reverse match any substring 1 A character , Returns if a character is not equal str location , All equal return -1*/
n= str.find_last_not_of("aBDC"); // Due to the str location 7'A', Not in the substring , so  n=7

Copy related:


str2=str1.substr(2);  // Extract the substring , Extract the str1 The subscript for 2 To the end , to str2
 
str2=str1.substr(2,3);  // Extract the substring , from  str1 The subscript for 2 start , extract 3 Bytes to str2
 
const char *s1= str.data(); // will string Class to an array of strings , Back to the s1
<br>
char *s=new char[10];
str.copy(s,count,pos); // will str In the pos Position to start , copy count A character , endures s In the .

Example 1, string class through the implementation of string loop right shift function

For example: "abcdefg" loop move 3 to the right until: "efgabcd"

The code is as follows:


#include <iostream>
#include <string>
#include <sstream>
 
using namespace std;
 
string operator >>(const string& str,int n)
{
  string ret;
  n %= str.length();
 
  ret=str.substr(str.length()-n);    // Find the right-shifted string 
  ret+=str.substr(0,str.length()-n); 
 
  return ret;
}
 
int main()
{ 
  string str="abcdefg";
  string ret= str>>3 ;
  cout<<ret<<endl;
 
  return 0;
}

Example 2, string inversion through the string class

Such as: "we; tonight; you "- > "ew;thginot;uoy"

The code is as follows:


#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
 
string reverse_func(const string& str)
{
  int end;
  int start=0;
  int len;
  string ret="";
  string tmp;
 
  while(1)
  {
   end=str.find(';',start);
 
   if(end== -1)   // Did not find ;
  {
   len=str.length()-start;
   tmp=str.substr(start,len);
 
   reverse(tmp.begin(),tmp.end()); // Reverse string 
 
   ret+=tmp;
 
   return ret;
  }
  else    // find ;
  {
   len=end-start;
   tmp=str.substr(start,len);
 
   reverse(tmp.begin(),tmp.end());  // Reverse string 
 
   ret+=tmp+';';
   start=end+1;
  }
 
  } 
 
}
 
int main()
{ 
  string str("we;tonight;you");
 
  string ret=reverse_func(str);
 
  cout<< ret<<endl;   
 
  return 0;
}

String to number conversion

Previously, in C, when we wanted to get the number in the string,1 was usually obtained through strtoul() or sscanf()

The C++ standard library also provides string and number conversion < sstream > Header files.

Two classes are needed:


string Common constructors of classes are :

string str;  // generate 1 Null string 
 
string str ("ABC") // Is equivalent to  str="ABC"<br>
string str ("ABC", strlen) //  will "ABC" endures str In the , Maximum pre-storage strlen bytes 
 
string s("ABC",stridx,strlen) // will "ABC" the stridx location , To start a string , endures str In the . Maximum storage strlen bytes .
 
string s(strlen, 'A') // storage strlen a 'A' to str In the 
0

Will string string - > The Numbers are used as follows


string Common constructors of classes are :

string str;  // generate 1 Null string 
 
string str ("ABC") // Is equivalent to  str="ABC"<br>
string str ("ABC", strlen) //  will "ABC" endures str In the , Maximum pre-storage strlen bytes 
 
string s("ABC",stridx,strlen) // will "ABC" the stridx location , To start a string , endures str In the . Maximum storage strlen bytes .
 
string s(strlen, 'A') // storage strlen a 'A' to str In the 
1

You can also convert temporary objects by writing:


string Common constructors of classes are :

string str;  // generate 1 Null string 
 
string str ("ABC") // Is equivalent to  str="ABC"<br>
string str ("ABC", strlen) //  will "ABC" endures str In the , Maximum pre-storage strlen bytes 
 
string s("ABC",stridx,strlen) // will "ABC" the stridx location , To start a string , endures str In the . Maximum storage strlen bytes .
 
string s(strlen, 'A') // storage strlen a 'A' to str In the 
2

Or write line 3 as macro:


#define TO_NUM(str,num)  (istringstream(str)>>num)
// It can also be written as a template function 

Will digital - > string string, used as follows


string Common constructors of classes are :

string str;  // generate 1 Null string 
 
string str ("ABC") // Is equivalent to  str="ABC"<br>
string str ("ABC", strlen) //  will "ABC" endures str In the , Maximum pre-storage strlen bytes 
 
string s("ABC",stridx,strlen) // will "ABC" the stridx location , To start a string , endures str In the . Maximum storage strlen bytes .
 
string s(strlen, 'A') // storage strlen a 'A' to str In the 
4

You can also write it through a macro like this:


string Common constructors of classes are :

string str;  // generate 1 Null string 
 
string str ("ABC") // Is equivalent to  str="ABC"<br>
string str ("ABC", strlen) //  will "ABC" endures str In the , Maximum pre-storage strlen bytes 
 
string s("ABC",stridx,strlen) // will "ABC" the stridx location , To start a string , endures str In the . Maximum storage strlen bytes .
 
string s(strlen, 'A') // storage strlen a 'A' to str In the 
5

Related articles: