C++ 字符串遍历:方法详解及代码示例

在 C++ 中,字符串可以使用循环遍历。以下是一种常见的遍历字符串的方法:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = 'Hello World';
    for (int i = 0; i < str.length(); i++) {
        cout << str[i] << ' ';  
    }
    return 0;
}

输出:

H e l l o   W o r l d

在上面的代码中,我们使用了 length() 函数来获取字符串的长度,然后使用循环遍历字符串中的每个字符并输出。

C++ 字符串遍历:方法详解及代码示例

原文地址: https://www.cveoy.top/t/topic/m0Yn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录