Home > Back-end >  How to iterate through every letter in a vector of strings?
How to iterate through every letter in a vector of strings?

Time:12-27

As mentioned in the title, how do I iterate through every letter in a vector of strings?

If someone types in some words like

hello
random
stack

and then enters a letter like e I want to print out which words contains the letter "e" which is "hello". So how do I check every character in the vector for that character and then print the word(s) out?

 for (int i {}; i < gift_bag.gifts.size();   i) 
    {
        if (gift_bag.gifts[i] == letter) 
        
        {
            cout << gift_bag.gifts[i] << endl;
        }
    }

This is what I've done but it is wrong because it check if a string is equal a character. I want to iterate through the letters in each word.

gift_bag is defined as Gift_Bag_Type which is a struct containing a vector<string> named gifts. And letter is char

CodePudding user response:

The ranged for loop and find function in std::string will help you.

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

int main()
{
    std::vector<std::string> vec = { "hello", "random", "stack" };
    constexpr char letter = 'e';

    for (const auto &str : vec)
        if (str.find(letter) != std::string::npos)
            std::cout << str << '\n'; // hello
}

CodePudding user response:

You'll need two loops, one to iterate through the vector, then a nested loop to iterate through the string.

const size_t vector_size = gift_bag.size();
for (unsigned int i = 0u; i < vector_size;   i)
{
    std::string& s(gift_bag[i]);
    const size_t string_size = s.length();
    for (unsigned int j = 0U; j < string_size;   j)
    {
        Process_Character(s[j]);
    }
}

There may be other methods, but you will need to consider that the strings may not be all the same length.

  •  Tags:  
  • c
  • Related