Comparing list of strings to char

so for my assignment I have to write a program. One of the function requires us to compare a char to a list of strings to see how many words are in that list that start with that char and then add it to another string.

My question is how do I compare the two? A char to the first letter in the string in the list
My question is how do I compare the two? A char to the first letter in the string in the list


1
2
3
4
5
6
7
8
char c = 'a';
std::string s = "apple";

// compare:
if (s[0] == c) // s[0] is the first character (letter) of the string.
{
    std::cout << "A for Apple!" << std::endl;
}


If you have an array/vector of strings, you would access the i'th string's first character as my_str_list[i][0].
Last edited on
Thanks for the reply but I don't need a array/vector of strings. I need the data structure list. A list of strings such as list<string> listOfWords;!
If you have a list of strings do it like this:
1
2
3
4
5
  list<string> words = {"Anna", "Lisa", "Katie", "Cassie"};
  for (const string& word : words)
  {
    // do your comparison here
  }
Thank you, how would I access the first character of the list? Would it be like:
1
2
list<string> words ={ “Anna”};
words[1]; 

I’m not sure of how to access the first character in the word
To access the first character [of the first word] of the list, you can do
1
2
  std::list<std::string> words = { "Anna" };
  std::cout << words.front()[0] << std::endl;


To iterate through the list, do something like the following:
1
2
3
4
5
6
std::list<std::string> words = { "Anna", "Leo", "Nikolai" };
 
for (auto it = words.begin(); it != words.end(); std::advance(it, 1))
{
    std::cout << (*it)[0] << std::endl;
}

Edit: or use Thomas's method to iterate (for each), it's cleaner.

(If you want to be able to access any word in constant time by index, use an array or std::vector instead.)
Last edited on
Topic archived. No new replies allowed.