不区分大小写的字符串比较C ++

时间:2012-02-07 19:54:53

标签: c++ case-insensitive string-comparison

我知道有一些方法可以做一些忽略比较,包括迭代字符串或一个good one SO需要另一个库。我需要把它放在其他可能没有安装它的计算机上。有没有办法使用标准库来做到这一点?现在我正在做...

if (foo == "Bar" || foo == "bar")
{
cout << "foo is bar" << endl;
}

else if (foo == "Stack Overflow" || foo == "stack Overflow" || foo == "Stack overflow" || foo == "etc.")
{
cout << "I am too lazy to do the whole thing..." << endl;
}

这可以极大地提高我的代码的可读性和可用性。感谢您阅读此内容。

5 个答案:

答案 0 :(得分:17)

strncasecmp

  

strcasecmp()函数执行字符串 s1 s2 的逐字节比较,忽略字符的大小写。如果 s1 分别小于,匹配或大于 s2 ,则返回小于,等于或大于零的整数。< / p>      

strncasecmp()函数类似,只是它比较 s1 s2 n 字节...

答案 1 :(得分:7)

通常我所做的只是比较一个较低版本的字符串版本,例如:

if (foo.make_this_lowercase_somehow() == "stack overflow") {
  // be happy
}

我相信boost内置了小写转换,所以:

#include <boost/algorithm/string.hpp>    

if (boost::algorithm::to_lower(str) == "stack overflow") {
  //happy time
}

答案 2 :(得分:3)

你为什么不把一切都做成小案,然后进行比较呢?

tolower()

  int counter = 0;
  char str[]="HeLlO wOrLd.\n";
  char c;
  while (str[counter]) {
    c = str[counter];
    str[counter] = tolower(c);
    counter++;
  }

  printf("%s\n", str);

答案 3 :(得分:2)

您可以编写一个简单的函数将现有字符串转换为小写,如下所示:

#include <string>
#include <ctype.h>
#include <algorithm>
#include <iterator>
#include <iostream>

std::string make_lowercase( const std::string& in )
{
  std::string out;

  std::transform( in.begin(), in.end(), std::back_inserter( out ), ::tolower );
  return out;
}

int main()
{
  if( make_lowercase( "Hello, World!" ) == std::string( "hello, world!" ) ) {
    std::cout << "match found" << std::endl;
  }

  return 0;
}

答案 4 :(得分:2)

我刚刚写了这个,也许它对某些人有用:

int charDiff(char c1, char c2)
{
    if ( tolower(c1) < tolower(c2) ) return -1;
    if ( tolower(c1) == tolower(c2) ) return 0;
    return 1;
}

int stringCompare(const string& str1, const string& str2)
{
    int diff = 0;
    int size = std::min(str1.size(), str2.size());
    for (size_t idx = 0; idx < size && diff == 0; ++idx)
    {
        diff += charDiff(str1[idx], str2[idx]);
    }
    if ( diff != 0 ) return diff;

    if ( str2.length() == str1.length() ) return 0;
    if ( str2.length() > str1.length() ) return 1;
    return -1;
}