共翁号
共翁号 > 常识 > string怎么用

string怎么用

原创2025-07-05 15:33:46

`string` 是 C++ 标准库中的一个类,用于处理字符串。以下是一些基本用法:

定义和初始化

直接初始化:使用小括号 `string s1;`

拷贝初始化:使用等号 `string s2 = s1;`

直接初始化,指定字符和数量:`string s3(10, 'c');`

直接初始化,从另一个字符串复制:`string s4(s3);`

字符串字面值初始化:`string s5("Hello World");`

读写字符串

从标准输入读取字符串:`string s; cin >> s;`

输出字符串:`cout << s;`

字符串长度和访问

获取字符串长度:`s.size();`

访问字符串中的字符:`s[i];`

获取指定位置的字符:`s.charAt(i);`

字符串比较

直接使用关系运算符比较字符串:`if (s1 == s2) { ... }`

字符串修改

连接字符串:`s1 = s1 + s2;`

替换字符串中的子串:`s.replace(loc, len, s);`

插入字符串:`s.insert(loc, s);`

删除字符串中的子串:`s.erase(loc, len);`

字符串查找

查找子串第一次出现的位置:`s.indexOf(s);`

查找子串最后一次出现的位置:`s.lastIndexOf(s);`

字符串判断

判断字符串是否包含某个子串:`s.contains(s);`

判断字符串是否为空:`s.isEmpty();`

字符串转换

字符串转字符数组:`char* c = s.toCharArray();`

字符数组转字符串:`string s(c);`

字符串转字节数组:`byte[] b = s.getBytes();`

其他操作

获取字符串的第一个字符:`s.front();`

获取字符串的最后一个字符:`s.back();`

获取字符串的迭代器:`s.begin();`、`s.end();`、`s.rbegin();`、`s.rend();`

示例代码

```cpp

include

include

using namespace std;

int main() {

// 定义和初始化字符串

string s1;

cin >> s1;

// 字符串长度

cout << "Length: " << s1.size() << endl;

// 访问字符串中的字符

for (int i = 0; i < s1.size(); i++) {

cout << s1[i] << " ";

}

cout << endl;

// 字符串连接

string s2 = " World";

s1 += s2;

cout << "Concatenated: " << s1 << endl;

// 字符串替换

s1.replace(0, 5, "Hi ");

cout << "Replaced: " << s1 << endl;

// 字符串插入

s1.insert(7, " beautiful");

cout << "Inserted: " << s1 << endl;

// 字符串删除

s1.erase(10, 5);

cout << "Erased: " << s1 << endl;

// 字符串查找

int pos = s1.indexOf("beautiful");

if (pos != string::npos) {

cout << "Found at position: " << pos << endl;

} else {

cout << "Not found" << endl;

}

return 0;

}

```

建议

在使用 `string` 时,尽量利用其提供的丰富方法,以提高代码的可读性和效率。

注意 `string` 是不可变的,因此在需要修改字符串内容时,可以考虑使用 `stringstream` 或其他可修改字符串的类。

在处理字符串时,经常查看 C++ 标准库的 API 文档,以充分利用其提供的各种功能。

返回:常识

相关阅读