不区分大小写的字符串比较C++
Case insensitive string comparison C++
我知道有一些方法可以进行大小写忽略比较,包括遍历字符串,或者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()
函数对字符串s1和s2执行逐字节比较,忽略字符大小写。如果发现s1分别小于、匹配或大于s2,则返回小于、等于或大于零的整数。
strncasecmp()
函数类似,只是它比较s1和s2的不超过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;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么比较运算符如此快速
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- C++自定义比较函数
- 如何比较自定义类的std::变体
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- std::设置自定义比较器
- 布尔比较运算符是如何在C++中工作的
- C++将目录中的所有文件与::filesystem进行比较
- shell排序中的交换和比较
- 如何在C++中比较两个char数组
- catch框架有没有办法比较流或文件
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 智能指针作为无序映射键,并通过引用进行比较
- 比较if语句中的数组值和int值
- 对于循环变体比较
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 比较两个大小不等的映射c++