类似这样的东西:
if (string.toLower() == "string") {
cout << "output";
}
我尝试使用:transform(input.begin(), input.end(), input.begin(), toupper);
没有结果。
答案 0 :(得分:3)
实际上,您可以将std::tolower()
与std::transform()
配合使用来实现此目的。例如:
#include <string>
#include <algorithm>
#include <cctype>
#include <iostream>
std::string to_lower(const std::string& s) {
std::string lower{s};
std::transform(lower.begin(), lower.end(), lower.begin(),
[](unsigned char c){ return std::tolower(c); });
return lower;
}
int main()
{
std::string str{"UPPER_CASE"};
if (to_lower(str) == "upper_case")
std::cout << "String matched.";
return 0;
}
输出:
String matched.
Note here对于std::tolower(int ch)
:“如果ch
的值不能表示为unsigned char
并且不等于EOF
,则行为是未定义的”。。因此, lambda 将unsigned char
作为std::transform
的第四个参数。
还要注意,upon NRVO for calls到to_lower()
进行这种优化时,不会复制任何额外的std::string
-对于保存小写版本的单个副本来说,不会复制一次。
答案 1 :(得分:1)
使用C ++ 17 if
with initializer
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string value {"Hello World"};
if (
std::string lower{value}, dummy{lower.end(), std::transform(
lower.begin(), lower.end(), lower.begin(),
[](unsigned char c){ return std::tolower(c); }
)};
!lower.compare("hello world")
) {
std::cout << "equal" << std::endl;
}
}
答案 2 :(得分:-1)
这是怎么回事:
string LowerCaseString(string str) {
string ret;
for (auto chr : str) {
ret += tolower(chr);
}
return ret;
}
if (LowerCaseString(somestring) == "string") {
// do something
}