C++ string类
时间: 2023-11-14 21:05:21 浏览: 173
C++中的string类是一个标准库类型,用于处理字符串。它提供了丰富的成员函数和操作符来操作和处理字符串。使用string类可以方便地进行字符串的初始化、比较、连接、截取等操作。
在C++中,可以使用C语言风格的字符串初始化string对象,例如:string str = "hello!";
而在C++中,可以使用关系运算符(==、!=、<、<=、>、>=)来比较两个string对象的大小。例如:
```cpp
#include <string>
#include <iostream>
using namespace std;
int main() {
string str1("hello");
string str2("hello");
if (str1 == str2)
cout << "str1 = str2" << endl;
else if (str1 < str2)
cout << "str1 < str2" << endl;
else
cout << "str1 > str2" << endl;
return 0;
}
```
这段代码将比较两个string对象的大小,并输出相应的结果。
除了比较操作,string类还提供了丰富的成员函数来进行字符串的操作。例如,可以使用erase函数删除字符串中的一部分字符。例如:
```cpp
#include <string>
#include <iostream>
using namespace std;
int main() {
string str("Hello,World!");
str.erase(5, 6); // 删除从索引位置5开始的6个字符
cout << "str为:" << str << endl;
return 0;
}
```
这段代码会删除字符串中从索引位置5开始的6个字符,并输出结果。
阅读全文
相关推荐













