Explain the usage and examples of C++

  • 2020-06-03 07:53:30
  • OfStack

string is an important part of the C++ standard library for string processing. It can be operated directly by means of input/output stream or by means of file. The C++ library also has good support for string, and string interfaces well with c strings. Although there are also some disadvantages, but the flaws outweigh the disadvantages.

Most of the code used is from the cpp website, because the examples are very complete.

Declaration and initialization methods:

To use string, first add it to the header file < string >
The declaration is also simple

Statement:


string s;// The statement 1 a string  object 
string ss[10];// The statement 1 a string Array of objects 

Initialization:

Initialization that USES the equal sign is called copy initialization, and initialization that does not use the equal sign is called direct initialization.


#include <bits/stdc++.h>
using namespace std;
int main()
{
 ios::sync_with_stdio(false);
 string s;// Default initialization, 1 Null string 
 string s1("ssss");//s1 It's in denominations." ssss A copy of the" 
 string s2(s1);//s2 is s1 A copy of the 
 string s3=s2;//s3 is s2 A copy of the 
 string s4(10,'c');// the s4 Initialize the 
 string s5="hiya";// Copy initialization 
 string s6=string(10,'c');// Copy initialization, generate 1 Three initialized objects, copy to s6
 //string s(cp,n)
 char cs[]="12345";
 string s7(cs,3);// Copy string cs The former 3 A character to s among 
 //string s(s2,pos2)
 string s8="asac";
 string s9(s8,2);// from s2 The first 2 Start copying characters, no more than 2 s2 the size
 //string s(s2,pos2,len2)
 string s10="qweqweqweq";
 string s11(s10,3,4);//s4 is s3 From the subscript 3 start 4 A copy of more than 2 characters s3.size Undefined appears 
 return 0;
}

String handling:

substr operation:

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";
 //s.substr(pos1,n) Returns a string position of pos1 At the back of the n A string of two characters 
 string s2=s.substr(1,5);//bcdef
 //s.substr(pos)// get 1 a pos The string to the end 
 string s3=s.substr(4);//efg
 return 0;
}

If the position of the input exceeds the length of the character, an out_of_range exception is thrown

insert operation:

The code is from cpp website, after their own collation

Note the difference between using iterators as arguments and unsigned Numbers as arguments


#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)// in s the pos Position insert str
 str.insert(6,str2);     // to be the question
 //s.insert(pos,str,a,n) in s the pos Position insert str Middle insertion position a To the back of the n A character 
 str.insert(6,str3,3,4);    // to be not the question
 //s.insert(pos,cstr,n)// in pos Position insert cstr String from the beginning to the end n A character 
 str.insert(10,"that is cool",8); // to be not that is the question
 //s.insert(pos,cstr) in s the pos Position insert cstr
 str.insert(10,"to be ");   // to be not to be that is the question
 //s.insert(pos,n,ch) in s.pos Insert above the position n a ch
 str.insert(15,1,':');    // to be not to be: that is the question
 //s.insert(s.it,ch) in s the it Insert ahead of the point position 1 A character ch , which returns the iterator at the newly inserted location 
 it = str.insert(str.begin()+5,','); // to be, not to be: that is the question
 //s.insert(s.it,n,ch)// in s the it Insert in front of the point position n a ch
 str.insert (str.end(),3,'.');  // to be, not to be: that is the question...
 //s.insert(it,str.ita,str.itb) in it Insert in front of the point position [ita,itb) The string 
 str.insert (it+2,str3.begin(),str3.begin()+3); // to be, or not to be: that is the question...
 return 0;
}

erase operation:

Used to perform a delete operation

There are three types of delete operations

Specify pos and len, where pos is the starting position and pos, followed by ES65en-1, is deleted Iterator, which removes the character that the iterator points to Iterator range, delete the string of this 1 range, range left closed right open

Code from cpp official website


#include <iostream>
#include <string>
int main ()
{
 std::string str ("This is an example sentence.");
 std::cout << str << '\n';
       // "This is an example sentence."
 str.erase (10,8);  //   ^^^^^^^^
 // Specifies the string position to delete directly 10 Behind a 8 A character 
 std::cout << str << '\n';
       // "This is an sentence."
 str.erase (str.begin()+9);//   ^
 // Deletes the character that the iterator points to 
 std::cout << str << '\n';
       // "This is a sentence."
       //  ^^^^^
 str.erase (str.begin()+5, str.end()-9);
 // Deletes iterator scope characters 
 std::cout << str << '\n';
       // "This sentence."
 return 0;
}

append and replace operations:

The append function can be used to append characters and strings to the end of a string. Since string is overloaded with operators, it can also be implemented with the += operation
repalce, as the name suggests, means replace, first delete, then add.

The code is from the cpp website, with its own explanation


#include <iostream>
#include <string>
int main ()
{
 std::string str;
 std::string str2="Writing ";
 std::string str3="print 10 and then 5 more";
 // Additional directly 1 a str2 The string 
 str.append(str2);      // "Writing "
 // attach str3 The first 6 It starts with two characters 3 A string 
 str.append(str3,6,3);     // "10 "
 // Appends the string parameter before it 5 A character 
 str.append("dots are cool",5);   // "dots "
 // Added directly 
 str.append("here: ");     // "here: "
 // add 10 a '.'
 str.append(10u,'.');     // ".........."
 // add str3 Iterator scoped string 
 str.append(str3.begin()+8,str3.end()); // " and then 5 more"
 // The last one is special, which means add 5 a 'A' , in fact, in the parameters 65 The corresponding asc Code is 65
 str.append<int>(5,65);    // "....."
 // String appends can also be implemented with the overload operator 
 str+="lalala";
 std::cout << str << '\n';
 return 0;
}

The use of replace, replace supports finding positions using unsigned integers as well as 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*123456789*12345
 std::string str=base;   // "this is a test string."
 // The first 9 And the following 4 A character is str2 Instead of 
 str.replace(9,5,str2);   // "this is an example string." (1)
 // The first 19 A string and the following 5 Characters with str The first 7 And the following 5 Character substitution 
 str.replace(19,6,str3,7,6);  // "this is an example phrase." (2)
 // The first 8 And the following 9 Characters are replaced by string parameters 
 str.replace(8,10,"just a");  // "this is just a phrase."  (3)
 // The first 8 And the following 5 Characters used before a string argument 7 Character substitution 
 str.replace(8,6,"a shorty",7); // "this is a short phrase." (4)
 // The first 22 And the following 0 Characters with 3 An exclamation point substitution 
 str.replace(22,1,3,'!');  // "this is a short phrase!!!" (5)
 // The principle of iterators is the same 
 // 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 above replace operation can be replaced with a combination of insert and erase operations, but replace is more convenient.

assign operation:

The assign operation exists in both 1-column containers, such as vector, and so on. string is a very basic operation function, string can be used to assign values flexibly.

The code is from the cpp 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 Assigned to str
 str.assign(base);
 std::cout << str << '\n';
 // the base The first 10 And the following 8 Two characters to str
 str.assign(base,10,9);
 std::cout << str << '\n';   // "brown fox"
 // Take the 0 to 6 A string to str
 str.assign("pangrams are cool",7);
 std::cout << str << '\n';   // "pangram"
 // Use parameter assignment directly 
 str.assign("c-string");
 std::cout << str << '\n';   // "c-string"
 // to str The assignment 10 a '*' character 
 str.assign(10,'*');
 std::cout << str << '\n';   // "**********"
 // The assignment is 10 a '-'
 str.assign<int>(10,0x2D);
 std::cout << str << '\n';   // "----------"
 // The specified base Iterator scoped string 
 str.assign(base.begin()+16,base.end()-12);
 std::cout << str << '\n';   // "fox jumps over"
 return 0;
}

string search operation:

The string class provides a number of excellent, easy-to-use member methods. And there are a lot of practical tricks in generic algorithms.

find and rfind functions:

The find function is used to find out if a string has been present in the calling string. It is case sensitive.

The code is from the cpp 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 find in the same order as above:
 // in str In search of regulation 1 An emerging needle , returns the location of the occurrence, otherwise returns the end 
 std::size_t found = str.find(str2);
 if (found!=std::string::npos)
 std::cout << "first 'needle' found at: " << found << '\n';
 // in str Among them, from no found+1 Starts to look up before the parameter string 6 A character 
 found=str.find("needles are small",found+1,6);
 if (found!=std::string::npos)
 std::cout << "second 'needle' found at: " << found << '\n';
 // in str Find the string in the argument 
 found=str.find("haystack");
 if (found!=std::string::npos)
 std::cout << "'haystack' also found at: " << found << '\n';
 // To find the 1 A character 
 found=str.find('.');
 if (found!=std::string::npos)
 std::cout << "Period found at: " << found << '\n';
 // Mix and match str2 Replace with a string from the argument table 
 // let's replace the first needle:
 str.replace(str.find(str2),str2.length(),"preposition");
 std::cout << str << '\n';
 return 0;
}

The rfind function looks for the last occurrence of a matching string and returns the same number of positions from front to back.


#include <bits/stdc++.h>
using namespace std;
int main()
{
 ios::sync_with_stdio(false);
 std::string str ("The sixth sick sheik's sixth sheep's sick.");
 std::string key ("sixth");//     ^
 //rfind Is to find the last 1 The occurrence of a matching string 
 std::size_t found = str.rfind(key);
 if (found!=std::string::npos)
 {
  cout<<found<<endl;// The output 23
  str.replace (found,key.length(),"seventh");// To find the sixth replace seventh
 }
 std::cout << str << '\n';
 return 0;
}

Search efficiency is very high, I have not seen stl source analysis, but the feeling is using kmp to achieve. Well, you can write one by yourself.

find_... of function:


#include <bits/stdc++.h>
using namespace std;
int main()
{
 ios::sync_with_stdio(false);
 string s;// Default initialization, 1 Null string 
 string s1("ssss");//s1 It's in denominations." ssss A copy of the" 
 string s2(s1);//s2 is s1 A copy of the 
 string s3=s2;//s3 is s2 A copy of the 
 string s4(10,'c');// the s4 Initialize the 
 string s5="hiya";// Copy initialization 
 string s6=string(10,'c');// Copy initialization, generate 1 Three initialized objects, copy to s6
 //string s(cp,n)
 char cs[]="12345";
 string s7(cs,3);// Copy string cs The former 3 A character to s among 
 //string s(s2,pos2)
 string s8="asac";
 string s9(s8,2);// from s2 The first 2 Start copying characters, no more than 2 s2 the size
 //string s(s2,pos2,len2)
 string s10="qweqweqweq";
 string s11(s10,3,4);//s4 is s3 From the subscript 3 start 4 A copy of more than 2 characters s3.size Undefined appears 
 return 0;
}
0

find_last_of and find_last_not_of are basically the same as first, so don't write the example code.

Comparison and conversion:

Similar to the c string comparison function, strcmp function 1 supports string comparison operations, while similar to the python, C# function 1 supports converting Numbers and strings. Some features are found in C++11.

Note the compiler bug:

In the MinGW compiler, if the version is less than 3.8, c++11 is supported, but there is one bug in it. To update the version of MinGW, or use g++.

compare function:

Like the strcmp function 1, if two strings are equal, then 0 is returned, and the calling object is greater than the argument and less than -1.

Partial comparisons are also supported in compare, where six parameters can be set.


#include <bits/stdc++.h>
using namespace std;
int main()
{
 ios::sync_with_stdio(false);
 string s;// Default initialization, 1 Null string 
 string s1("ssss");//s1 It's in denominations." ssss A copy of the" 
 string s2(s1);//s2 is s1 A copy of the 
 string s3=s2;//s3 is s2 A copy of the 
 string s4(10,'c');// the s4 Initialize the 
 string s5="hiya";// Copy initialization 
 string s6=string(10,'c');// Copy initialization, generate 1 Three initialized objects, copy to s6
 //string s(cp,n)
 char cs[]="12345";
 string s7(cs,3);// Copy string cs The former 3 A character to s among 
 //string s(s2,pos2)
 string s8="asac";
 string s9(s8,2);// from s2 The first 2 Start copying characters, no more than 2 s2 the size
 //string s(s2,pos2,len2)
 string s10="qweqweqweq";
 string s11(s10,3,4);//s4 is s3 From the subscript 3 start 4 A copy of more than 2 characters s3.size Undefined appears 
 return 0;
}
1

Since string is overloaded with operators, it can be used directly > , < , == to compare, it is also very convenient.

Numerical conversion:

In the section of io, there are examples of conversion between values and strings. The stringstream function is used. In c++11, there is a ready-made function call defined, which is very convenient.

string和数值转换  
to_string(val) 把val转换成string
stoi(s,p,b) 把字符串s从p开始转换成b进制的int
stol(s,p,b) long
stoul(s,p,b) unsigned long
stoll(s,p,b) long long
stoull(s,p,b) unsigned long long
stof(s,p) float
stod(s,p) double
stold(s,p) long double


#include <bits/stdc++.h>
using namespace std;
int main()
{
 ios::sync_with_stdio(false);
 string s;// Default initialization, 1 Null string 
 string s1("ssss");//s1 It's in denominations." ssss A copy of the" 
 string s2(s1);//s2 is s1 A copy of the 
 string s3=s2;//s3 is s2 A copy of the 
 string s4(10,'c');// the s4 Initialize the 
 string s5="hiya";// Copy initialization 
 string s6=string(10,'c');// Copy initialization, generate 1 Three initialized objects, copy to s6
 //string s(cp,n)
 char cs[]="12345";
 string s7(cs,3);// Copy string cs The former 3 A character to s among 
 //string s(s2,pos2)
 string s8="asac";
 string s9(s8,2);// from s2 The first 2 Start copying characters, no more than 2 s2 the size
 //string s(s2,pos2,len2)
 string s10="qweqweqweq";
 string s11(s10,3,4);//s4 is s3 From the subscript 3 start 4 A copy of more than 2 characters s3.size Undefined appears 
 return 0;
}
2

conclusion


Related articles: