简体   繁体   中英

Iterate through the chars in a string array?

In C++ I have an array of strings, say:

string lines[3]

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

is there a way to loop through the chars within each index as well as loop through the indexes? something like lines[i[j]] ?

If you have C++11, you can use range for loop and auto:

// 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

abcdefg

hijklm

Try this code:

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];
    }
}

Yes.

#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;
}

Use a double loop. For each line, iterate through each character. Using a double index isn't exactly allowed like this: arr[i,j] or arr[i[j]] ; it needs to be arr[i][j] .

But, if you're using a std::string , you need just either iterate over the str.length() or just use for (auto it : str) , where str = THE TYPE OF std::string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM