get first character of a string from a string vector

14,922

Solution 1

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

Solution 2

Rather than writing a loop here at all, I'd use a standard algorithm. For example, to display all the strings (one per line) that start with the specified letter, you could use something like this:

std::copy_if(vec.begin(), vec.end(), 
             std::ostream_iterator<std::string>(std::cout, "\n"),
             [ch](std::string const &s) { return s[0] == ch; });

Solution 3

To get the string at index k of the vector, the following code should work:

vector<string>::iterator i = vec.begin();
while (i != vec.end())
{
  if (i - vec.begin() == k)
    cout << (*i) << endl;
  ++i;
}

To get the character from that string, you can dereference at the appropriate position.

Share:
14,922
helix
Author by

helix

Updated on June 13, 2022

Comments

  • helix
    helix almost 2 years

    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')|