简体   繁体   English

如何在if语句c ++中将字符串转换为较低的字符串

[英]How do I convert a string to lower within an if statement c++

Something like this: 像这样的东西:

if (string.toLower() == "string") {
    cout << "output";
}

I have tried using: transform(input.begin(), input.end(), input.begin(), toupper); 我尝试过使用: transform(input.begin(), input.end(), input.begin(), toupper); with no results. 没有结果。

Indeed you can use std::tolower() with std::transform() to achieve this. 实际上你可以使用std::tolower()std::transform()来实现这一点。 For example: 例如:

#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;
}

Output: 输出:

String matched.

Note here that for std::tolower(int ch) : "If the value of ch is not representable as unsigned char and does not equal EOF , the behavior is undefined" . 请注意 ,对于std::tolower(int ch)“如果ch的值不能表示为unsigned char且不等于EOF ,则行为未定义” Hence the lambda taking an unsigned char as the 4th argument to std::transform . 因此lambdaunsigned char作为std::transform的第4个参数。

Also note that upon NRVO for calls to to_lower() , should such optimization takes place, no extra std::string is being copied -- beyond once for the single one necessary to hold the lower case version. 还要注意, 在NRVO调用 to_lower() ,如果发生这样的优化,则不会复制额外的std::string - 超过一次持有小写版本所需的单个。

Using C++17 if with initializer if使用初始化程序, if使用C ++ 17

#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;
    }
}

what about something like this : 这样的事情怎么样:

string LowerCaseString(string  str) {
  string ret;
  for (auto chr : str) {
      ret += tolower(chr);
  }
  return ret;
}

if (LowerCaseString(somestring) == "string") {
     // do something
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM