Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through the chars in a string array?

Tags:

c++

arrays

string

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]]?

like image 739
Austin Avatar asked Oct 27 '25 23:10

Austin


2 Answers

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];
    }
}
like image 154
Tim Biegeleisen Avatar answered Oct 30 '25 15:10

Tim Biegeleisen


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

like image 22
Steephen Avatar answered Oct 30 '25 13:10

Steephen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!