怎么遍历字符串c++
时间: 2025-03-08 17:13:47 浏览: 89
### C++ 中遍历字符串的方法
在 C++ 中,有多种方式可以用来遍历字符串。以下是几种常见的方法:
#### 使用基于范围的 `for` 循环
这种方法简洁明了,适用于不需要索引的情况。
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "example";
for (char c : str) {
std::cout << c;
}
}
```
此代码片段展示了如何通过基于范围的 `for` 循环来逐字符访问字符串中的每一个元素[^1]。
#### 使用传统 `for` 循环与下标操作符
当需要知道当前处理的是哪一个位置上的字符时,这种做法非常有用。
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "example";
for (size_t i = 0; i < str.length(); ++i) {
char currentChar = str[i];
std::cout << currentChar;
}
}
```
这段程序利用传统的 `for` 循环以及数组风格的下标运算符来获取并打印每个字符。
#### 利用迭代器进行遍历
对于更复杂的场景或者想要写出更具泛型特性的代码来说,使用标准库提供的迭代器是一个不错的选择。
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "example";
auto it = str.begin();
while (it != str.end()) {
std::cout << *it++;
}
}
```
这里演示了借助于容器类成员函数返回的输入/输出迭代器来进行遍历的方式[^2]。
阅读全文
相关推荐




















