如何在 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'
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。