Hi guys! I'm trying to write a little program that would do these tasks in order:
Ex:
******************************************
Enter a word : alabama
Enter a letter you want to search: a
Result:
Letter a found in position 1,3,5 and 7.
*******************************************
I've been trying to code it with strstr but I can't make it work with the cin fonction.
If you just want to find a single character, you don't need to use substring. But either way, you just need to start your search after the previously found result.
Thanks and great documentation. I'm still having a hard time finding all the positions of a certain letter, it seems that only the first position is showed.
Any tips here?
Thanks for you that. I just added the find function and it seems to work but the problem is that it only gives me the first occurence of the letter I'm searching. It looks like I have to add something to word.find(letter) but I can't get it. I need all position occurences, how can I do that?
You can only get one occurrence at a time. Once you find an occurrence you need to search again but this time start after the occurrence you just found. Repeat this process until you can no longer find another occurrence.
#include <iostream>
#include <string>
int main()
{
constint maxchar = 10;
std::string word ;
std::cout << "Enter a word(Max " << maxchar << " char): " ;
std::cin >> word ;
// if( word.size() > maxchar ) etc.
/*string*/ char letter; // use the type char to hold one character
// const int maxletter = 1;
std::cout << "Enter the letter you want to find: " ;
std::cin >> letter ;
std::cout << "Your word: " << word << '\n'
<< "Your letter: " << letter << '\n'
<< "The letter '" << letter << "' is found at positions: " ;
for( std::size_t pos = 0 ; pos < word.size() ; ++pos )
{
if( word[pos] == letter ) std::cout << pos << ' ' ;
}
std::cout << '\n' ;
}