Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get first character of a string from a string vector

how to get the first character or how to get a character by index from a string in a string vector while iterating through that vector. Here's my code:

vector<string>::iterator i=vec.begin();
    while(i!=vec.end()){
        if(i[0]==ch)
            cout<<"output";
    }

it's giving the error:

no match for 'operator==' (operand types are 'std::basic_string' and 'char')|

like image 700
helix Avatar asked Dec 11 '22 00:12

helix


1 Answers

Try the following

vector<string>::iterator i=vec.begin();
    while(i!=vec.end()){
        if(i[0][0] == ch)
            cout<<"output";
        ++i;
    }

i[0] returns the whole string pointed to by iterator i while i[0][0] returns the first character of the string even if the string is empty (in this case the value will be '\0'). :)

But you could write simpler

for ( const std::string &s : vec )
{
    if ( s[0] == ch ) cout << "output";
}

If you want to use some index that can have any value then the code could look like

vector<string>::iterator i=vec.begin();
    while(i!=vec.end()){
        if( index < i[0].size() && i[0][index] == ch)
            cout<<"output";
        ++i;
    }

Or

for ( const std::string &s : vec )
{
    if ( index < s.size() && s[index] == ch ) cout << "output";
}
like image 173
Vlad from Moscow Avatar answered Jan 31 '23 19:01

Vlad from Moscow