2012-02-07 151 views
6

我知道有办法做案例忽略比较,涉及遍历字符串或一个good one SO上需要另一个库。我需要把它放在其他可能没有安装的计算机上。有没有办法使用标准库来做到这一点?现在我只是在做...不区分大小写的字符串比较C++

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

这可以大大提高我的代码的可读性和可用性。感谢您阅读这些。

+2

认真吗?即使没有内置的方式,你也可以很容易地编写一个函数来做到这一点,而不是蛮横强迫每一个单独的比较。遍历字符串有什么问题?这就是你要使用的任何图书馆都会做的。 – 2012-02-07 19:58:06

+3

stricmp无处不在。 – arx 2012-02-07 20:01:15

+0

可用的标准库取决于您计划使用哪种版本的C++编译器来编译二进制文件。例如,C++ 0x具有正则表达式支持。对于较老的编译器,可以使用stricmp。 – Alan 2012-02-07 20:05:32

回答

15

strncasecmp

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

strncasecmp()功能类似,只是它比较不超过ň字节S1S2 ...

+0

谢谢,这终于奏效了! – CoffeeRain 2012-02-07 20:08:03

+3

@CoffeeRain:非常欢迎您!我很高兴你喜欢简单的旧学校C功能超过曼波C++通心粉:) – 2012-02-07 21:44:17

+0

它应该是空白的? – nfoggia 2014-02-10 17:17:02

2

你为什么不让小写字母变小写然后比较一下?

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); 
+0

我正在尝试这种方式,但它工作得不是很好。你能提供一个例子吗?我会尝试发布我的错误代码... – CoffeeRain 2012-02-07 19:59:19

6

平时我做什么,只是比较一个小写的版本有问题的字符串,如:

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

我相信升压内置了小写转换的话, :

#include <boost/algorithm/string.hpp>  

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

Boost是我链接到的那个...我没有那个。 – CoffeeRain 2012-02-07 20:00:14

+0

boost在任何意义上都是免费的,如果出于某种原因无法安装它,则可以将to_lower算法从其中取出。 – 2012-02-09 15:38:33

+1

'to_lower'的返回值是无效的。你必须首先应用'to_lower',然后照常进行比较。在gcc上面,会给你一个'不值得忽略的空值,因为它应该是'错误。 – Fadecomic 2012-10-31 19:50:20

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; 
} 
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; 
} 
相关问题