【问题标题】:How to perform case insensitive string comparison? [duplicate]如何执行不区分大小写的字符串比较? [复制]
【发布时间】: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&lt;char&gt; 是这种情况,谢谢。
  • 在比较它们之前小写 2 个字符串。
  • @dfri 我的担忧与std::basic_string 无关,它适用于every 编程语言中的every 字符串类型。诚然,C++ 字符串更糟糕,因为 tolowertoupper 已损坏。

标签: c++ string visual-c++


【解决方案1】:

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

#include <algorithm>

...
if (std::tolower(x) == std::tolower(y)) { 
    ...
}
...

【讨论】:

  • 不要使用tolowertoupper 来实现不区分大小写的比较。对于 x = "STRASSE"y = "straße",这将失败,它们应该比较相等。
  • 为什么“STRASSE”和“straße”应该相等? “SS”不等于“ß”。
  • 因为这就是德语正字法的规定 (DIN 5007-1)。
  • 那是错误的。德语中不存在“Strasse”一词。 “大街”是正确的。 korrekturen.de/beliebte_fehler/strasse.shtml 目前,已引入大写“ß”。 de.wikipedia.org/wiki/Gro%C3%9Fes_%C3%9F
  • 这完全无关紧要。字符串比较(通常)不限于“现有”单词(对于“现有”的给定定义),它控制字符串排序规则。否则你也可以说“straße”在德语中不是一个词,只有“Straße”是。然而,如果你走过你的城镇,你应该会注意到“STRASSE”的拼写确实确实存在,即使在高度官方的文物中也是如此。
【解决方案2】:

来自here的解决方案

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

【讨论】:

  • 不要使用tolowertoupper 来实现不区分大小写的比较。对于 x = "STRASSE"y = "straße",这将失败,它们应该比较相等。
  • 但这不是最初问题的一部分。
猜你喜欢
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
相关资源
最近更新 更多