对于字符串中 character/substring 的每个实例
For every instance of a character/substring in string
我在 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!
我在 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!