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

Case insensitive string comparison C++

本问题已经有最佳答案,请猛点这里访问。

我知道有一些方法可以做case-ignore比较,包括遍历字符串或一个好的字符串,因此需要另一个库。我需要把这个放在其他可能没有安装它的计算机上。有没有一种方法可以使用标准库来做到这一点?现在我只是在做…

1
2
3
4
5
6
7
8
9
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;
}

这可以大大提高代码的可读性和可用性。谢谢你读到这里。


StrucaseCMP

The strcasecmp() function performs a byte-by-byte comparison of the strings s1 and s2, ignoring the case of the characters. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

The strncasecmp() function is similar, except that it compares no more than n bytes of s1 and s2...


通常我所做的只是比较问题字符串的小写版本,比如:

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

我相信Boost有内置的小写转换,所以:

1
2
3
4
5
#include <boost/algorithm/string.hpp>    

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


你为什么不先把所有的事情都放低一点再比较呢?

托洛韦()

1
2
3
4
5
6
7
8
9
10
11
12
  int counter = 0;
  char str[]="HeLlO wOrLd.
"
;
  char c;
  while (str[counter]) {
    c = str[counter];
    str[counter] = tolower(c);
    counter++;
  }

  printf("%s
"
, str);


我刚刚写了这篇文章,也许对某人有用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
#include <ctype.h>
#include
#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;
}