检查字符串是否包含子字符串,无论大小写

Han*_*fei 3 c++ string parsing substring

假设我有一些字符串,str。

我要检查 str 是否包含关键字:“samples” 但是,“samples”可以是任何形式的大写形式,例如:“Samples”、“SamPleS”、“SAMPLES”。

这就是我正在尝试的:

string str = "this is a FoO test";
if (str.find("foo") != std::string::npos){
    std::cout << "WORKS";
}
Run Code Online (Sandbox Code Playgroud)

这不会检测到“FoO”子字符串。有什么我可以通过的参数来忽略大写吗?还是我应该完全使用其他东西?

Sha*_*y D 6

将两个字符串都转换为大写:

std::string upperCase(std::string input) {
  for (std::string::iterator it = input.begin(); it != input.end(); ++ it)
    *it = toupper((unsigned char)*it);
  return input;
}
Run Code Online (Sandbox Code Playgroud)

然后使用find()像:

upperCase(str).find(upperCase(target))
Run Code Online (Sandbox Code Playgroud)