string container
string container
The basic concept of a string.
Essence:
- A string in C++ is a string in the C++ style, and string is fundamentally a class.
*Difference between string and char :
- char * is a pointer.
- A string is a class that encapsulates a
char*internally, managing the string and serving as a container of typechar*.
Features:
The String class internally encapsulates many member methods.
例如:查找 find,拷贝 copy,删除 delete,替换 replace,插入 insert
String manages the memory allocated for char*, eliminating concerns about copying overflows or value retrieval overflows, as the class handles this internally.
string constructor
Constructor Prototype:
string();//Create an empty string, for example: string str;string(const char* s);//Initialize with string sstring(const string& str);//Initialize one string object with anotherstring(int n, char c);// Initialize with n characters c
Example:
#include <string>
//string构造
void test01()
{
string s1; //创建空字符串,调用无参构造函数
cout << "str1 = " << s1 << endl;
const char* str = "hello world";
string s2(str); //把c_string转换成了string
cout << "str2 = " << s2 << endl;
string s3(s2); //调用拷贝构造函数
cout << "str3 = " << s3 << endl;
string s4(10, 'a');
cout << "str3 = " << s3 << endl;
}
int main() {
test01();
return 0;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Summary: The various ways to construct a string aren't comparable—just use whichever works best.
string assignment operation
Functional description:
- 给string字符串进行赋值
Function prototype for assignment:
string& operator=(const char* s);// Assigning a char* type string to the current stringstring& operator=(const string &s);//assign string s to the current stringstring& operator=(char c);//Assign character to current stringstring& assign(const char *s);//assign string s to the current stringstring& assign(const char *s, int n);//assigns the first n characters of string s to the current stringstring& assign(const string &s);//Assign string s to the current stringstring& assign(int n, char c);//assign n characters c to the current string
Example:
//赋值
void test01()
{
string str1;
str1 = "hello world";
cout << "str1 = " << str1 << endl;
string str2;
str2 = str1;
cout << "str2 = " << str2 << endl;
string str3;
str3 = 'a';
cout << "str3 = " << str3 << endl;
string str4;
str4.assign("hello c++");
cout << "str4 = " << str4 << endl;
string str5;
str5.assign("hello c++",5);
cout << "str5 = " << str5 << endl;
string str6;
str6.assign(str5);
cout << "str6 = " << str6 << endl;
string str7;
str7.assign(5, 'x');
cout << "str7 = " << str7 << endl;
}
int main() {
test01();
return 0;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Summary:
There are many ways to assign strings, and operator= is quite practical.
string concatenation
Description:
- Implement appending a string to the end of a string.
Function prototype:
string& operator+=(const char* str);//Overload += operatorstring& operator+=(const char c);//Overload += operatorstring& operator+=(const string& str);//Overload += operatorstring& append(const char *s);//Concatenate string s to the end of the current stringstring& append(const char *s, int n);//Concatenate the first n characters of string s to the end of the current stringstring& append(const string &s);//same as operator+=(const string& str)string& append(const string &s, int pos, int n);//Append n characters starting from position pos in string s to the end of the string
Example:
//字符串拼接
void test01()
{
string str1 = "我";
str1 += "爱玩游戏";
cout << "str1 = " << str1 << endl;
str1 += ':';
cout << "str1 = " << str1 << endl;
string str2 = "LOL DNF";
str1 += str2;
cout << "str1 = " << str1 << endl;
string str3 = "I";
str3.append(" love ");
str3.append("game abcde", 4);
//str3.append(str2);
str3.append(str2, 4, 3); // 从下标4位置开始 ,截取3个字符,拼接到字符串末尾
cout << "str3 = " << str3 << endl;
}
int main() {
test01();
return 0;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Summary: There are many overloaded versions of string concatenation. In the initial stage of learning, just remember a few.
String search and replace
Description:
- Search for the specified string
- Replace: Replace the string at the specified position
Function prototype:
int find(const string& str, int pos = 0) const;//Finds the first occurrence of str starting from posint find(const char* s, int pos = 0) const;//Find the first occurrence of 's', starting the search from position 'pos'int find(const char* s, int pos, int n) const;//Find the first occurrence of the first n characters of s starting from posint find(const char c, int pos = 0) const;// Find the first occurrence of character cint rfind(const string& str, int pos = npos) const;//Find the last occurrence of a string, starting the search from posint rfind(const char* s, int pos = npos) const;// Find the last occurrence position of 's', starting search from posint rfind(const char* s, int pos, int n) const;//Find the last position of the first n characters of string s starting from posint rfind(const char c, int pos = 0) const;//Find the last occurrence position of character cstring& replace(int pos, int n, const string& str);//replace n characters starting from pos with string strstring& replace(int pos, int n,const char* s);//Replace n characters starting at position pos with string s
Example:
//查找和替换
void test01()
{
//查找
string str1 = "abcdefgde";
int pos = str1.find("de");
if (pos == -1)
{
cout << "未找到" << endl;
}
else
{
cout << "pos = " << pos << endl;
}
pos = str1.rfind("de");
cout << "pos = " << pos << endl;
}
void test02()
{
//替换
string str1 = "abcdefgde";
str1.replace(1, 3, "1111");
cout << "str1 = " << str1 << endl;
}
int main() {
//test01();
//test02();
return 0;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Summary:
- find searches from left to right, rfind from right to left
- The find function returns the position of the first character when a string is found, and returns -1 if it is not found.
- When using replace, you need to specify the starting position, the number of characters, and the string to replace them with.
String comparison
Description:
- String comparison
Comparison Method:
- String comparison is performed based on the ASCII codes of the characters.
= return 0
Back 1
< return -1
Function prototype:
int compare(const string &s) const;//compare with string sint compare(const char *s) const;//compare with string s
Example:
//字符串比较
void test01()
{
string s1 = "hello";
string s2 = "aello";
int ret = s1.compare(s2);
if (ret == 0) {
cout << "s1 等于 s2" << endl;
}
else if (ret > 0)
{
cout << "s1 大于 s2" << endl;
}
else
{
cout << "s1 小于 s2" << endl;
}
}
int main() {
test01();
return 0;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Summary: String comparison is primarily used to check whether two strings are equal, as determining which is greater or smaller isn’t particularly meaningful.
string character access
There are two ways to access a single character in a string:
- Using the square bracket operator
[]: This provides direct access to the character at the specified index. For example,str[index]. - Using the
at()method: This also accesses the character at a given index but includes bounds checking. If the index is out of range, it throws anout_of_rangeexception. For example,str.at(index).
char& operator[](int n);//take characters using methodchar& at(int n);//Using the at method to get the character
Example:
void test01()
{
string str = "hello world";
for (int i = 0; i < str.size(); i++)
{
cout << str[i] << " ";
}
cout << endl;
for (int i = 0; i < str.size(); i++)
{
cout << str.at(i) << " ";
}
cout << endl;
//字符修改
str[0] = 'x';
str.at(1) = 'x';
cout << str << endl;
}
int main() {
test01();
return 0;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Summary: There are two ways to access individual characters in a string: using brackets or the at method.
String Insertion and Deletion
Description:
- Perform insertion and deletion operations on a string
Function prototype:
string& insert(int pos, const char* s);//insert stringstring& insert(int pos, const string& str);//insert stringstring& insert(int pos, int n, char c);//Insert n characters 'c' at the specified position.string& erase(int pos, int n = npos);// Delete n characters starting from Pos
Example:
//字符串插入和删除
void test01()
{
string str = "hello";
str.insert(1, "111");
cout << str << endl;
str.erase(1, 3); //从1号位置开始3个字符
cout << str << endl;
}
int main() {
test01();
return 0;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Summary: Both insertion and deletion start indexing from 0.
string substring
Description:
- Extracting the desired substring from a string.
Function prototype:
- return the string composed of n characters starting from pos
Example:
//子串
void test01()
{
string str = "abcdefg";
string subStr = str.substr(1, 3);
cout << "subStr = " << subStr << endl;
string email = "hello@sina.com";
int pos = email.find("@");
string username = email.substr(0, pos);
cout << "username: " << username << endl;
}
int main() {
test01();
return 0;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Summary: Flexible use of substring function can extract useful information in practical development.