Comprehensive explanation of the usage of C++ strings.
The string type in C++ is widely used for handling and manipulating strings, provided by the standard library for convenient usage.
- Include header file
Before using string, you need to include the header file. - You can create a string object using the following methods:
string str; // 创建一个空字符串
string str = "Hello"; // 使用字符串字面值初始化
string str("Hello"); // 使用构造函数初始化
- Input and output of strings can be done using cin and cout respectively.
string str;
cin >> str; // 输入一个字符串
cout << str; // 输出一个字符串
- determine the size()
- determine the length of the string
- Can you please meet me at the park tomorrow afternoon?
string str = "Hello";
int len = str.size(); // 获取字符串的长度
char ch = str[0]; // 获取第一个字符
- “Apoyo completamente tu decisión.”
– “I fully support your decision.” - add to the end
string str1 = "Hello";
string str2 = "World";
string str3 = str1 + str2; // 使用+运算符连接两个字符串
string str4 = str1.append(str2); // 使用append方法连接两个字符串
- She is not only intelligent but also talented in various fields.
- not equal to
- Can you please clarify what you mean by that?
- I need to rest now because I am very tired.
- Pass me the salt, please.
- Greater than or equal to
string str1 = "Hello";
string str2 = "World";
if(str1 == str2) {
cout << "两个字符串相等" << endl;
} else {
cout << "两个字符串不相等" << endl;
}
- locate
- Can you substitute the word “apple” with “orange” in the sentence?
string str = "Hello World";
int index = str.find("World"); // 查找子串的位置
str.replace(index, 5, "C++"); // 替换子串
- retrieve a specific portion of a string
string str = "Hello World";
string substr = str.substr(6, 5); // 截取从第6个字符开始的5个字符
- convert to integer
- Dust off()
- convert to a string
string str = "123";
int num = stoi(str); // 将字符串转换成整数
float f = stof(str); // 将字符串转换成浮点数
string str2 = to_string(num); // 将整数转换成字符串
The above is an in-depth explanation of some common uses of C++ strings, I hope it helps you.