如何执行不区分大小写的字符串比较?

How to perform case insensitive string comparison?

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

在此代码中,我正在比较两个字符串,我做对了,但我不想考虑字母的大小写。

例如:第一个字符串:AAAAA,第二个字符串:AAAA。输出应为 0 或等于。

有什么想法可以解决这个问题吗?

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() 
{
cout << "enter the first string" << endl;
string x; 
cin >> x;
cout << "enter the second string" << endl;
string y; 
cin >> y;
cout << endl;
sort(x.begin(), x.end());
sort(y.begin(), y.end());
cout << x << endl;
cout << y << endl;
if (x.compare(y) < 0)
{
cout << "-1" << endl;
}
if (x.compare(y) > 0)
{
cout << "1" << endl;
}
if (x.compare(y) == 0)
{
cout << "0" << endl;
}
} 

您可以使用std::tolower将字符串xy转换为其小写表示形式,然后比较两个小写字符串。

#include <algorithm>
...
if (std::tolower(x) == std::tolower(y)) { 
...
}
...

从这里开始的解决方案

if (std::toupper(x) == std::toupper(y)) {
cout << "0" << endl;
}