如何在 C++ 中遍历字符串
Jinku Hu
2023年1月30日
2020年11月24日
本文将介绍关于在 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'
Author: Jinku Hu
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn