aj1204
aj1204

Reputation: 57

How to refer to specific character of a string in a string vector?

I need to double-loop through the characters of each string in a vector array and am getting stuck on how what the syntax would be to call each character of each element.

Upvotes: 1

Views: 961

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

Here are shown different approaches

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::vector<std::string> v = { "Hello", "World" };

    for ( const auto &s : v )
    {
        for ( auto c : s ) std::cout << c;
        std::cout << ' ';
    }

    std::cout << std::endl;

    for ( auto i = v.size(); i != 0; )
    {
        for ( auto j = v[--i].size(); j != 0; ) std::cout << v[i][--j];
        std::cout << ' ';
    }

    std::cout << std::endl;

    for ( auto it1 = v.begin(); it1 != v.end(); ++it1 )
    {
        for ( auto it2 = it1->rbegin(); it2 != it1->rend(); ++it2 ) std::cout << *it2;
        std::cout << ' ';
    }

    std::cout << std::endl;

}    

The program output is

Hello World 
dlroW olleH 
olleH dlroW 

You can combine these approaches in various ways.

If you want to change a character in a string using the range-based for statement then you have to write the loops the following way

    for ( auto &s : v )
    {
        for ( auto &c : s ) /* assign something to c */;
    }

Upvotes: 0

David Haim
David Haim

Reputation: 26496

the vector [] operator will return std::string&, then you use [] operator of std::string to get the character (as char&).

std::vector<std::string> vec{"hello","world"};
std::cout<<vec[0][3];

as @RyanP commented, the method std::vector::at and std::string::at will preform boundry check and will throw an exception if you try to dereference an index which is bigger than the vector/string size.

try{
   std::cout<<vec.at(0).at(3); 
}
catch (std::exception& e){
  //handle
}

Upvotes: 7

Slava
Slava

Reputation: 44258

As you need to iterate over string in a vector, ie use it multiple times, create a (const) reference:

std::vector<std::string> vec { "abc", "efg" };
for( size_t i = 0; i < vec.size(); ++i ) {
    const auto &str = vec[i];
    for( size_t j = 0; j < str.length(); ++j )
        std::cout << str[j];
}

Otherwise you would have to write vec[i][j] multiple times, which is too verbose

Upvotes: 0

Related Questions