如何执行不区分大小写的字符串比较?
How to perform case insensitive string comparison?
在此代码中,我正在比较两个字符串,我做对了,但我不想考虑字母的大小写。
例如:第一个字符串: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
将字符串x
和y
转换为其小写表示形式,然后比较两个小写字符串。
#include <algorithm>
...
if (std::tolower(x) == std::tolower(y)) {
...
}
...
从这里开始的解决方案
if (std::toupper(x) == std::toupper(y)) {
cout << "0" << endl;
}
相关文章:
- 编写宏函数来更改字符串的大小写?
- 如何执行不区分大小写的字符串比较?
- 对字符串向量进行排序,但不区分大小写
- 如何创建一个程序来标识最长的子字符串回文,而不考虑字母大小写
- 哈希字符串更改大小写
- 在字符串的 boost::unordered_set 中使用 Lambda 函数 - 不区分大小写
- 开关大小写语句中函数中的字符串输入会导致无限循环和绕过输入
- 比较字符串大小写不区分的简单方法是什么?
- 使用 std::string 返回开关大小写块中的字符串常量
- 如何使字符串中的每个字母不区分大小写
- 不区分大小写的字符串
- 是否有函数/WinAPI 可以判断一个字符串是否以不区分大小写的语言方式以另一个字符串开头?
- 使用 map<string,int> 在开关大小写语句中使用字符串
- 处理从 std::istream 中提取字符串的空字符串大小写
- C++大小写中的类型转换常量字符串
- C++,检查两个字符串的不区分大小写相等
- 在字符串向量中查找字符串,不区分大小写的c++
- 如何按大小写顺序排列字符串(而不是按字典顺序排列)
- 内置C++函数,使两个字符串的比较不区分大小写
- 使用 std::unique_copy 从向量中提取不区分大小写的唯一字符串