Home > Back-end >  For every instance of a character/substring in string
For every instance of a character/substring in string

Time:04-10

So I have this string in C that looks like this:

string word = "substring"

Now I want it to read the word string, and create a FOR LOOP for each time there is an s in the word string, and print out "S found!". The end result should be:

S found!
S found!

CodePudding user response:

Maybe you could utilize toupper:

#include <iostream>
#include <string>

void FindCharInString(const std::string &str, const char &search_ch) {
  const char search_ch_upper = toupper(search_ch, std::locale());
  for (const char &ch : str) {
    if (toupper(ch, std::locale()) == search_ch_upper) {
      std::cout << search_ch_upper << " found!\n";
    }
  }
}

int main() {
  std::string word = "substring";
  std::cout << word << '\n';
  FindCharInString(word, 's');
  return 0;
}

Output:

substring
S found!
S found!
  • Related