C++ string detailed explanation, C++ string detailed explanation

C++  has greatly enhanced its support for strings. In addition to using C-style strings, you can also use the built-in string class. The string class is much more convenient for processing strings and can completely replace the character array or string pointer in C language .

String is a commonly used class in C++. It is very important and we need to explain it separately here.

To use the string class, you need to include a header file <string>. The following example introduces several methods of defining string variables (objects):

 
 
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main(){
  5. string s1;
  6. string s2 = "c plus plus";
  7. string s3 = s2;
  8. string s4 (5, 's');
  9. return 0;
  10. }

The variable s1 is only defined but not initialized. The compiler will assign a default value to s1, ""which is an empty string.

The variable s2 is initialized to when it is defined "c plus plus". Unlike C-style strings, there is no end mark at the end of a string '\0'.

The variable s3 is directly initialized with s2 when it is defined, so the content of s3 is also initialized "c plus plus".

The variable s4 is initialized to a string consisting of 5 's'characters, that is "sssss". As can be seen from the above code, string variables can be assigned

directly through the assignment operator . =String variables can also be assigned values ​​using C-style strings. For example, s2 is initialized with a string constant, and s3 is initialized with the s2 variable.

Unlike C-style strings, when we need to know the length of a string, we can call the length() function provided by the string class. As follows:

 
 
  1. string s = "http://c.biancheng.net";
  2. int len = s.length();
  3. cout<<len<<endl;

The output result is 22. Since there are no characters at the end of the string '\0', length() returns the actual length of the string, not the length + 1.

Convert to C-style string

Although C++ provides the string class to replace strings in the C language, in actual programming, sometimes C-style strings must be used (such as the path when opening a file). For this reason, the string class provides us with a Conversion function c_str(), this function can convert a string string into a C-style string and return the const pointer of the string (const char*). Please look at the code below:

 
 
  1. string path = "D:\\demo.txt";
  2. FILE *fp = fopen(path.c_str(), "rt");

In order to open a file using the fopen() function in C, the string must be converted to a C-style string.

string input and output of string

The string class overloads the input and output operators, and you can treat string variables like ordinary variables, that is, use them for >>input and use <<them for output. Please look at the code below:

 
 
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main(){
  5. string s;
  6. cin>>s; //Input string
  7. cout<<s<<endl; //output string
  8. return 0;
  9. }

Running results:
http://c.biancheng.net http://vip.biancheng.net↙
http://c.biancheng.net

Although we entered two URLs separated by spaces, only one was output. This is because the input operator >>ignores spaces by default and considers the input to end when encountering a space, so the last input http://vip.biancheng.netis not stored in the variable s.

Access characters in a string

Each character in a string string can also be accessed by subscript just like a C-style string. The starting index of string string still starts from 0. Please look at the code below:

 
 
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main(){
  5. string s = "1234567890";
  6. for(int i=0,len=s.length(); i<len; i++){
  7. cout<<s[i]<<" ";
  8. }
  9. cout<<endl;
  10. s[5] = '5';
  11. cout<<s<<endl;
  12. return 0;
  13. }

Running results:
1 2 3 4 5 6 7 8 9 0
1234557890

This example defines a string variable s and assigns the value "1234567890", and then uses a  for loop to traverse and output each character. With the help of subscripts, in addition to being able to access each character, you can also modify each character. The s[5] = '5';sixth character is modified to '5', so s ends up being "1234557890".

String concatenation

With the string class, we can use +the OR +=operator to directly splice strings, which is very convenient. We no longer need to use strcat(), strcpy(), malloc() and other functions in C language to splice strings. Don’t worry about overflowing if there’s not enough space.

When used to+ concatenate strings, both sides of the operator can be string strings, a string string and a C-style string, a string string and a character array, or a string character. string and a single character. Please see the following example:

 
 
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main(){
  5. string s1 = "first ";
  6. string s2 = "second ";
  7. char *s3 = "third ";
  8. char s4[] = "fourth ";
  9. char ch = '@';
  10. string s5 = s1 + s2;
  11. string s6 = s1 + s3;
  12. string s7 = s1 + s4;
  13. string s8 = s1 + ch;
  14. cout<<s5<<endl<<s6<<endl<<s7<<endl<<s8<<endl;
  15. return 0;
  16. }

Running results:
first second
first third
first fourth
first @

String addition, deletion, modification and query

The string class provided by C++ contains several practical member functions, which greatly facilitates operations such as adding, deleting, changing, and querying strings.

1. Insert string

The insert() function can insert another string at the specified position in the string string. One of its prototypes is:

string& insert (size_t pos, const string& str);

pos represents the position to be inserted, which is the subscript; str represents the string to be inserted, which can be a string string or a C-style string.

Please look at the code below:

 
 
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main(){
  5. string s1, s2, s3;
  6. s1 = s2 = "1234567890";
  7. s3 = "aaa";
  8. s1.insert(5, s3);
  9. cout<< s1 <<endl;
  10. s2.insert(5, "bbb");
  11. cout<< s2 <<endl;
  12. return 0;
  13. }

Running results:
12345aaa67890
12345bbb67890

The first parameter of the insert() function may go out of bounds. If it goes out of bounds, a runtime exception will occur. We will explain in detail how to catch this exception in the chapter " C++ Exception (Exception) ".

For more prototypes and usage of the insert() function, please refer to: http://www.cplusplus.com/reference/string/string/insert/

2. Delete string

The erase() function can delete a substring in string. One of its prototypes is:

string& erase (size_t pos = 0, size_t len = npos);

pos represents the starting subscript of the substring to be deleted, and len represents the length of the substring to be deleted. If len is not specified, all characters from pos to the end of the string are directly deleted (at this time len = str.length - pos).

Please look at the code below:

 
 
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main(){
  5. string s1, s2, s3;
  6. s1 = s2 = s3 = "1234567890";
  7. s2.erase(5);
  8. s3. erase(5, 3);
  9. cout<< s1 <<endl;
  10. cout<< s2 <<endl;
  11. cout<< s3 <<endl;
  12. return 0;
  13. }

Running results:
1234567890
12345
1234590

Some readers are worried that when the pos parameter does not go out of bounds, the len parameter may also cause the substring to be deleted to go out of bounds. But in fact, this will not happen. The erase() function will take the smallest one from the following two values ​​as the length of the substring to be deleted:

  • the value of len;
  • The length of the string minus the value of pos.


To put it simply, the string to be deleted can only be deleted up to the end of the string.

3. Extract substring

The substr() function is used to extract substrings from string strings. Its prototype is:

string substr (size_t pos = 0, size_t len = npos) const;

pos is the starting index of the substring to be extracted, and len is the length of the substring to be extracted.

Please look at the code below:

 
 
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main(){
  5. string s1 = "first second third";
  6. string s2;
  7. s2 = s1.substr(6, 6);
  8. cout<< s1 <<endl;
  9. cout<< s2 <<endl;
  10. return 0;
  11. }

Running results:
first second third
second

The system processes the substr() parameters similarly to erase():

  • If pos is out of bounds, an exception will be thrown;
  • If len is out of bounds, all characters from pos to the end of the string will be extracted.

4. String search

The string class provides several functions related to string search, as shown below.

1) find() function

The find() function is used to find the position where a substring appears in a string string. Its two prototypes are:

size_t find (const string& str, size_t pos = 0) const;
size_t find (const char* s, size_t pos = 0) const;

The first parameter is the substring to be found, which can be a string or a C-style string. The second parameter is the position (subscript) where the search starts; if not specified, the search starts from the 0th character.

Please look at the code below:

 
 
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main(){
  5. string s1 = "first second third";
  6. string s2 = "second";
  7. int index = s1.find(s2,5);
  8. if(index < s1.length())
  9. cout<<"Found at index : "<< index <<endl;
  10. else
  11. cout<<"Not found"<<endl;
  12. return 0;
  13. }

Running results:
Found at index: 6

The find() function ultimately returns the starting index of the first occurrence of the substring in the string. In this example, the s2 string is finally found at index 6. If the substring is not found, string::npos will be returned, which is a static constant member defined within the string class and is used to represent the maximum value that the size_t type can store.

2) rfind() function

rfind() is very similar to find(). It also searches for substrings in a string. The difference is that the find() function starts from the second parameter and searches backward, while the rfind() function searches up to the second parameter. At the parameter, if the substring has not been found by the subscript specified by the second parameter, string::npos is returned.

Please see the following example:

 
 
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main(){
  5. string s1 = "first second third";
  6. string s2 = "second";
  7. int index = s1.rfind(s2,6);
  8. if(index < s1.length())
  9. cout<<"Found at index : "<< index <<endl;
  10. else
  11. cout<<"Not found"<<endl;
  12. return 0;
  13. }

Running result:
Found at index : 6

3) find_first_of() function

The find_first_of() function is used to find the first occurrence of a character in a string that is common to both a substring and a string. Please look at the code below:

 
 
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main(){
  5. string s1 = "first second second third";
  6. string s2 = "asecond";
  7. int index = s1.find_first_of(s2);
  8. if(index < s1.length())
  9. cout<<"Found at index : "<< index <<endl;
  10. else
  11. cout<<"Not found"<<endl;
  12. return 0;
  13. }

Running result:
Found at index: 3

In this example, the character shared by s1 and s2 is 's'. The first subscript of this character in s1 is 3, so the search result returns 3.

Guess you like

Origin blog.csdn.net/m0_73557158/article/details/133409293