【问题标题】:Why is std:string not returning 0 on comparing sub strings of same text?为什么 std:string 在比较相同文本的子字符串时不返回 0?
【发布时间】:2020-11-21 10:05:51
【问题描述】:

这可能是一些简单的疏忽,但我对为什么第二次比较在以下代码中没有返回 0 感到困惑:

#include <iostream>

int main()
{
    std::string text =  "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
    std::string text2 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

    int result = text2.compare(text);

    if (result == 0)
    {
        std::cout << "strings same" << std::endl;
    }
    else
    {
        std::cout << "strings NOT same" << std::endl;
    }

    result = text2.compare(0, 10, text);

    if (result == 0)
    {
        std::cout << "strings same" << std::endl;
    }
    else
    {
        std::cout << "strings NOT same" << std::endl;
    }
}

【问题讨论】:

  • 仔细阅读docs。它将所有texttext2 的前10 个字符进行比较,这不相等。
  • @fredrik - 明白了!愿意发表您的评论作为答案吗?
  • 你想要text2.compare(0, text.length(), text)。或者,实际上,由于您要比较的只是子字符串的相等性,而不是实际的排序顺序,因此您想要的可能是 std::equal: std::equal(std::cbegin(text), std::next(std::cbegin(text), 10), std::cbegin(text2), std::next(std::cbegin(text2), 10))

标签: c++ stdstring


【解决方案1】:

这是因为 compare 函数在传递 pos & len 参数时,将整个第一个字符串与第二个字符串进行比较。第一个字符串比您要比较的第二个字符串的一部分长。

如果你也将第一个字符串作为子字符串,那么它将返回 true

result = text2.compare(0, 10, text, 0, 10);

上面的调用调用了这个重载

int compare (size_t pos, size_t len, const string& str,
         size_t subpos, size_t sublen) const;

subpos & sublen 是要比较的第一个字符串的 pos 和长度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 2012-07-20
    • 2020-02-23
    • 2012-04-12
    • 2019-12-21
    • 2015-06-13
    相关资源
    最近更新 更多