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

Case insensitive string comparison C++

本文关键字:比较 C++ 字符串 大小写 不区      更新时间:2023-10-16

我知道有一些方法可以进行大小写忽略比较,包括遍历字符串,或者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;
}

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

strncasecmp

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

strncasecmp()函数类似,只是它比较s1s2的不超过n字节。。。

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

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
}

为什么不把所有东西都写得小写,然后进行比较?

tolower()

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

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

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

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

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