c++string常用功能
时间: 2023-11-24 12:51:04 浏览: 32
以下是C++中string常用的功能:
一、字符串赋值
1. 使用赋值运算符=进行字符串赋值
```cpp
string str1 = "hello";
string str2 = str1;
```
2. 使用构造函数进行字符串赋值
```cpp
string str1("hello");
string str2(str1);
string str3("hello", 3); // str3的值为"hel"
string str4(5, 'a'); // str4的值为"aaaaa"
```
3. 使用assign函数进行字符串赋值
```cpp
string str1;
str1.assign("hello");
string str2;
str2.assign("hello", 3); // str2的值为"hel"
string str3;
str3.assign(str1);
string str4;
str4.assign(5, 'a'); // str4的值为"aaaaa"
```
二、字符串拼接
1. 使用加号+进行字符串拼接
```cpp
string str1 = "hello";
string str2 = "world";
string str3 = str1 + " " + str2; // str3的值为"hello world"
```
2. 使用append函数进行字符串拼接
```cpp
string str1 = "hello";
string str2 = "world";
str1.append(" ");
str1.append(str2); // str1的值为"hello world"
```
三、字符串比较
1. 使用比较运算符进行字符串比较
```cpp
string str1 = "hello";
string str2 = "world";
if (str1 == str2) {
// 两个字符串相等
} else if (str1 < str2) {
// str1小于str2
} else {
// str1大于str2
}
```
2. 使用compare函数进行字符串比较
```cpp
string str1 = "hello";
string str2 = "world";
int result = str1.compare(str2);
if (result == 0) {
// 两个字符串相等
} else if (result < 0) {
// str1小于str2
} else {
// str1大于str2
}
```
四、字符串查找
1. 使用find函数进行字符串查找
```cpp
string str = "hello world";
int pos = str.find("world"); // pos的值为6
```
2. 使用rfind函数进行反向字符串查找
```cpp
string str = "hello world";
int pos = str.rfind("l"); // pos的值为9
```