对于字符串中字符/子字符串的每个实例



我在C++中有一个字符串,看起来像这样:

string word = "substring"

我想使用for循环读取word字符串,每次找到s时,打印出"S found!"。最终结果应该是:

S found!
S found!

也许您可以使用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;
}

输出:

substring
S found!
S found!

最新更新