Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For every instance of a character/substring in string

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading