循环访问字符串数组中的字符

Iterate through the chars in a string array?

本文关键字:字符 数组 访问 字符串 循环      更新时间:2023-10-16

在C++中,我有一个字符串数组,比如:

string lines[3]
lines[0] = 'abcdefg'
lines[1] = 'hijklmn'
lines[2] = 'opqrstu'

有没有办法遍历每个索引中的字符以及遍历索引? 像lines[i[j]]

试试这段代码:

std::string lines[3];
lines[0] = "abcdefg";
lines[1] = "hijklmn";
lines[2] = "opqrstu";
for (int i=0; i < lines.length(); ++i) {
    for (int j=0; j < lines[i].length(); ++j) {
        std::cout << lines[i][j];
    }
}

如果您有 C++11,则可以使用 range for 循环和自动:

// Example program
#include <iostream>
#include <string>
int main()
{
   std::string lines[3];
   lines[0]="abcdefg";
   lines[1]="hijklm";
// for( auto line: lines)//using range for loop and auto here
   for(int i=0; i<3; ++i)
   {
       std::string::iterator it= lines[i].begin();
       //for ( auto &c : line[i]) //using range for loop and auto here
       for(; it!= lines[i].end(); ++it)
       {
           std::cout<<*it;
       }
       std::cout<<"n";
  }
}

O/P

阿克德夫

希克勒姆

是的。

#include <iostream>
#include <string>
int main() {
    std::string arr[3];
    arr[0] = "abcdefg";
    arr[1] = "defghij";
    arr[2] = "ghijklm";

    for(size_t i = 0; i < 3; ++i) {
        for (auto it : arr[i]) {
            std::cout << it;
        }
        std::cout << 'n';
    }
    return 0;
}

使用双循环。对于每一行,遍历每个字符。像这样使用双索引并不完全允许:arr[i,j]arr[i[j]];它需要arr[i][j].

但是,如果您使用的是std::string,则只需迭代str.length()或仅使用for (auto it : str),其中str = THE TYPE OF std::string