如何在 C++ 中遍历字符串
本文将介绍关于在 C++ 中如何在保持索引数的情况下对一个字符串进行遍历的多种方法。
在 C++ 中使用基于范围的循环来遍历一个字符串
现代 C++ 语言风格推荐对于支持的结构,进行基于范围的迭代。同时,当前的索引可以存储在一个单独的 size_t
类型的变量中,每次迭代都会递增。注意,增量是用变量末尾的++
运算符来指定的,因为把它作为前缀会产生一个以 1 开头的索引。下面的例子只显示了程序输出的一小部分。
#include <iostream>
#include <string>
using std::cout; using std::cin;
using std::endl; using std::string;
int main(){
string text = "They talk of days for which they sit and wait";
size_t index = 0;
for (char c : text) {
cout << index++ << " - '" << c << "'" << endl;
}
return EXIT_SUCCESS;
}
输出:
0 - 'T'
1 - 'h'
2 - 'e'
...
43 - 'i'
44 - 't'
在 C++ 中使用 for
循环遍历字符串
它在传统的 for
循环中具有优雅和强大的功能,因为当内部范围涉及矩阵/多维数组操作时,它提供了灵活性。当使用高级并行化技术(如 OpenMP 标准)时,它也是首选的迭代语法。
#include <iostream>
#include <string>
using std::cout; using std::cin;
using std::endl; using std::string;
int main(){
string text = "They talk of days for which they sit and wait";
for (int i = 0; i < text.length(); ++i) {
cout << i << " - '" << text[i] << "'" << endl;
}
return EXIT_SUCCESS;
}
输出:
0 - 'T'
1 - 'h'
2 - 'e'
...
43 - 'i'
44 - 't'
或者,我们可以使用 at()
成员函数访问字符串的单个字符。
#include <iostream>
#include <string>
using std::cout; using std::cin;
using std::endl; using std::string;
int main(){
string text = "They talk of days for which they sit and wait";
for (int i = 0; i < text.length(); ++i) {
cout << i << " - '" << text.at(i) << "'" << endl;
}
return EXIT_SUCCESS;
}
输出:
0 - 'T'
1 - 'h'
2 - 'e'
...
43 - 'i'
44 - 't'
相关文章
如何在 Pandas 中遍历 DataFrame 的行
发布时间:2024/04/20 浏览次数:90 分类:Python
-
我们可以使用索引属性 loc(),iloc(),iterrows(),itertuples(),iteritems()和 apply()方法遍历 Pandas 中的行。
使用 .forEach() 迭代 JavaScript 中的元素
发布时间:2024/03/21 浏览次数:174 分类:JavaScript
-
了解如何使用 .forEach() 方法迭代集合中的元素并调用函数对每个元素执行计算。
在 JavaScript 中遍历 Map
发布时间:2024/03/21 浏览次数:62 分类:JavaScript
-
JavaScript 允许借助键值对数据结构(即 Map)遍历对象。迭代过程以多种方式运行,例如在 ES6 之前的格式中,我们逐个遍历每个元素、for of 和 for 每个约定。
在 Python 中遍历 JSON 对象
发布时间:2023/12/20 浏览次数:193 分类:Python
-
本教程演示了如何在 Python 中遍历 json 对象JSON (JavaScript Object Notation) 是一种流行的数据格式,用于存储和交换数据。