租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

详解C++中string的用法和例子,c++ string的常用方法及其功能

发布时间:2023-08-17 07:55:35

详解C++中string的用法和例子

在C++中,string是一个表示字符串的标准库类。它提供了许多成员函数和操作符,用于在字符串中履行各种操作。
以下是一些常见的string用法和例子:
1. 创建string对象:
```
string str1; // 创建一个空字符串
string str2 = "Hello"; // 用字符串"Hello"初始化str2
string str3(str2); // 使用另外一个string对象初始化str3
```
2. 连接两个字符串:
```
string str1 = "Hello";
string str2 = " World";
string result = str1 + str2; // 连接str1和str2,结果为"Hello World"
```
3. 比较两个字符串:
```
string str1 = "apple";
string str2 = "banana";
if (str1 == str2) {
cout << "str1和str2相等" << endl;
} else if (str1 < str2) {
cout << "str1小于str2" << endl;
} else {
cout << "str1大于str2" << endl;
}
```
4. 获得字符串长度:
```
string str = "Hello";
int length = str.length(); // 获得字符串的长度,结果为5
```
5. 获得子字符串:
```
string str = "Hello World";
string sub = str.substr(6, 5); // 获得从位置6开始的5个字符,结果为"World"
```
6. 查找字符串:
```
string str = "Hello World";
int pos = str.find("World"); // 查找子字符串"World"在str中的位置,结果为6
```
7. 替换字符串中的子字符串:
```
string str = "Hello World";
str.replace(6, 5, "C++"); // 替换从位置6开始的5个字符为"C++",结果为"Hello C++"
```
8. 转换为C风格字符串:
```
string str = "Hello";
const char* cstr = str.c_str(); // 将string对象转换为C风格的字符串
```
这只是string类的一小部份用法和例子。在实际开发中,string类非常灵活和方便,可以处理各种字符串操作。