c++string函数
时间: 2023-08-27 14:07:05 浏览: 50
C++ 中的 string 类型提供了很多有用的函数来操作字符串。以下是一些常用的 string 函数:
1. length():返回字符串的长度。
2. substr():返回一个子串。
3. find():查找字符串中第一次出现某个字符串的位置。
4. replace():替换字符串中的子串。
5. append():在字符串末尾添加新的字符或字符串。
6. insert():在指定位置插入新的字符或字符串。
7. erase():从字符串中删除指定的字符或子串。
8. compare():按字典顺序比较两个字符串。
以下是一些示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello, ";
string str2 = "World!";
string str3 = str1 + str2;
cout << "str3: " << str3 << endl; // 输出:Hello, World!
cout << "str3.length(): " << str3.length() << endl; // 输出:13
cout << "str3.substr(0, 5): " << str3.substr(0, 5) << endl; // 输出:Hello
cout << "str3.find(\"World\"): " << str3.find("World") << endl; // 输出:7
str3.replace(7, 5, "Universe");
cout << "str3: " << str3 << endl; // 输出:Hello, Universe!
str3.append(" Goodbye!");
cout << "str3: " << str3 << endl; // 输出:Hello, Universe! Goodbye!
str3.insert(13, " Cruel ");
cout << "str3: " << str3 << endl; // 输出:Hello, Universe! Cruel Goodbye!
str3.erase(7, 8);
cout << "str3: " << str3 << endl; // 输出:Hello, Cruel Goodbye!
string str4 = "hello";
string str5 = "world";
int cmp = str4.compare(str5);
if (cmp == 0) {
cout << "str4 and str5 are equal" << endl;
} else if (cmp < 0) {
cout << "str4 is less than str5" << endl;
} else {
cout << "str4 is greater than str5" << endl;
}
return 0;
}
```