
📝string类的常用接口
string网址查询:https://legacy.cplusplus.com/reference/string/string/
🌠 string类对象的遍历和修改

| 函数名称 | 功能说明 |
|---|---|
| operator[] (重点) | 返回pos位置的字符,const string类对象调用 |
| begin+ end | begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器 |
| rbegin + rend | begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器 |
范围for | C++11支持更简洁的范围for的新遍历方式 |
🌉operator[]

作用:返回对字符串中位置 pos 处的字符的引用。
std::string::operator[] 是 C++ 标准库中 std::string 类的一个成员函数操作符重载。它用于访问 std::string 对象中的单个字符。
pos参数是一个size_t类型的索引值,用于指定要访问的字符在字符串中的位置。索引从 0 开始,最大值为string.size() - 1, 如果 pos超出了字符串的范围,行为是未定义的,可能会导致程序崩溃或其他错误。因此在使用时需要注意检查索引是否合法。operator[]`的定义大致如下,能自动检查
class string
{
public:
// 引用返回
// 1、减少拷贝
// 2、修改返回对象
char& operator[](size_t i)
{
assert(i < _size);
return _str[i];
}
private:
char* str;
size_t _size;
size_t _capacity;
};
- 非
const版本返回一个对字符的引用,可以用来修改字符。
char& operator[](size_t pos);
非 `const` 版本返回一个对字符的引用,可以用来修改字符。
实战例子:
int main()
{
string s1("hello C++");
s1[0] = 'x';
cout << s1.size() << endl;
for (size_t i = 0; i < s1.size(); i++)
{
s1[i]++;
}
cout << endl;
s1[2] = 'x';
//越界检查
s1[20];
for (size_t i = 0; i < s1.size(); i++)
{
//cout << s1.operator[](i) << " ";
cout << s1[i] << " ";
}
cout << endl;
for (size_t i = 0; i < s1.size(); i++)
{
cout << s1.operator[](i) << " ";
//cout << s1[i] << " ";
}
cout << endl;
return 0;
}

2. 该const 版本返回一个对字符的常量引用,只能用来读取字符。
只读不能修改
const char& operator[](size_t pos) const;
实例:
const string s2("helloc C++");
//不能修改
s2[0] = 'x';
cout << endl;

🌠迭代器iterator

std::string::iterator 是 C++ 标准库中 std::string 类的一种迭代器类型。它允许你遍历和访问 std::string 对象中的字符。
🌉begin与end
>begin返回指向字符串第一个字符的迭代器。

end返回的是字符串最后一个字符之后的字符,就是\0
例子:
string s1("hello C++");
string::iterator it = s1.begin();
while (it != s1.end())
{
cout << *it << endl;
++it;
}


🌉反向迭代器rbegin与rend
reverse_iterator rend() noexcept;
rbegin返回指向字符串的最后一个字符(即其反向开头)的反向迭代器。
rbegin返回指向字符串的最后一个字符(即其反向开头)的反向迭代器。
int main()
{
string s2("hello String");
string::reverse_iterator it2 = s2.rbegin();
while (it2 != s2.rend())
{
//*it2 += 3;
cout << *it2 << " ";
++it2;
}
cout << endl;
return 0;
}


对于const版本
const_reverse_iterator rend() const noexcept;
例如:
string s3("hello C++");
string::const_reverse_iterator it3 = s3.rbegin();
while (it3 != s3.rend())
{
cout << *it3 << endl;
*it3++;
}
cout << endl;
只读不可改

🌉范围for()
string s3("hello C++");
for (auto& e : s3)
{
e++;
cout << e << " ";
}
cout << endl;
cout << s3 << endl;
底层角度也是迭代器

在范围 for 循环中,使用了 auto& 来声明迭代器变量 e。这意味着 e 是对原始字符的引用,而不是副本。因此,对 e 的修改会直接影响到 s3 中的字符。递增字符 e 的操作(e++)实际上是修改了 s3 中的字符。这是因为 e 是对 s3 中字符的引用。
如果只是想读取字符串而不修改它,通常会使用 const auto& 来声明迭代器变量,以避免意外修改字符串的内容。

e只是副本,如果想改变加引用&
string s3("hello C++");
for (auto e : s3)
{
e++;
cout << e << " ";
}
cout << endl;
cout << s3 << endl;

🚩总结

本文详细介绍了C++中string类的常用接口,包括operator[]用于访问单个字符,迭代器(begin,end,rbegin,rend)用于遍历和修改字符串,以及范围for的使用。特别强调了索引访问、常量和可变引用的区别,以及迭代器在不同场景下的应用。



1410

被折叠的 条评论
为什么被折叠?



