How to find the size of a single index of string vector and print index if size equals a specific number?

Viewed 325

I have a vector of strings and now I want to print a single index of that vector if the size of that index equals 4, for example.

std::vector<string> str = {"Time", "Hello", "User"};

I know how to iterate through the vector and print out the indices but I do not know how to get the size of, for example, the first index ("Time") which I then want to print to the console.

Just need a few hints here :)

Thank you.

1 Answers

Have a look at std::string::size() and If you are comfort with range loop

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

int main()
{
    std::vector<std::string> str = {"Time", "Hello", "User"};

    for (const auto &s: str)
    {
        if(s.size() == 4) 
        {
            std::cout<<s;
            break;
        }
    }

    return 0;
}

or an Iterator

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

int main()
{
    std::vector<std::string> str = {"Time", "Hello", "User"};

    for (auto s = str.begin(); s != str.end(); s++)
    {
        if(s->size() == 4)
        {
            std::cout<<(*s);
            break;
        }
    }

    return 0;
}

Hope this helps, Thanks.

Related