【发布时间】:2020-06-16 07:28:19
【问题描述】:
在这段代码中,我在两个字符串之间进行比较,我做对了,但我不想考虑字母的大小写。
例如:第一个字符串:aaaa,第二个字符串: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;
}
}
【问题讨论】:
-
您可以在比较之前将两个输入字符串转换为小写;参见例如How to convert std::string to lower case?.
-
@dfri 不,这是一个糟糕的解决方案。一些国际字符串会失败。
-
@KonradRudolph 啊,我不知道
std::basic_string<char>是这种情况,谢谢。 -
在比较它们之前小写 2 个字符串。
-
@dfri 我的担忧与
std::basic_string无关,它适用于every 编程语言中的every 字符串类型。诚然,C++ 字符串更糟糕,因为tolower和toupper已损坏。
标签: c++ string visual-c++