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.

  1. Include header file
    Before using string, you need to include the header file .
  2. You can create a string object using the following methods:
string str; // 创建一个空字符串
string str = "Hello"; // 使用字符串字面值初始化
string str("Hello"); // 使用构造函数初始化
  1. Input and output of strings can be done using cin and cout respectively.
string str;
cin >> str; // 输入一个字符串
cout << str; // 输出一个字符串
  1. determine the size()
  2. determine the length of the string
  3. Can you please meet me at the park tomorrow afternoon?
string str = "Hello";
int len = str.size(); // 获取字符串的长度
char ch = str[0]; // 获取第一个字符
  1. “Apoyo completamente tu decisión.”
    – “I fully support your decision.”
  2. add to the end
string str1 = "Hello";
string str2 = "World";
string str3 = str1 + str2; // 使用+运算符连接两个字符串
string str4 = str1.append(str2); // 使用append方法连接两个字符串
  1. She is not only intelligent but also talented in various fields.
  2. not equal to
  3. Can you please clarify what you mean by that?
  4. I need to rest now because I am very tired.
  5. Pass me the salt, please.
  6. Greater than or equal to
string str1 = "Hello";
string str2 = "World";
if(str1 == str2) {
    cout << "两个字符串相等" << endl;
} else {
    cout << "两个字符串不相等" << endl;
}
  1. locate
  2. 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++"); // 替换子串
  1. retrieve a specific portion of a string
string str = "Hello World";
string substr = str.substr(6, 5); // 截取从第6个字符开始的5个字符
  1. convert to integer
  2. Dust off()
  3. 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.

bannerAds