迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > C++ >

如何在 C++ 中遍历字符串

作者:迹忆客 最近更新:2023/04/08 浏览次数:

本文将介绍关于在 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'

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

在 JavaScript 中遍历 Map

发布时间:2024/03/21 浏览次数:62 分类:JavaScript

JavaScript 允许借助键值对数据结构(即 Map)遍历对象。迭代过程以多种方式运行,例如在 ES6 之前的格式中,我们逐个遍历每个元素、for of 和 for 每个约定。

遍历 C# 中的列表

发布时间:2024/01/03 浏览次数:206 分类:编程语言

有 3 种主要方法可用于遍历 C# 中的列表,for 循环,foreach 循环和 Lambda 表达式。

在 Python 中遍历 JSON 对象

发布时间:2023/12/20 浏览次数:193 分类:Python

本教程演示了如何在 Python 中遍历 json 对象JSON (JavaScript Object Notation) 是一种流行的数据格式,用于存储和交换数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便