C++ 字符串和字符串文字比较

2023-11-30

所以我想简单地做一个std::string == "string-literal"这会工作得很好,除了我正在创建我的字符串

std::string str(strCreateFrom, 0, strCreateFrom.find(' '));

并找到回报string::npos现在这两个都包含字符串"submit"然而==返回 false,现在我已将范围缩小到尺寸“不同”的事实,即使它们实际上并非如此。str.size()是 7 并且strlen("submit")是 6。这是为什么吗?==失败了,我认为是这样,但我不明白为什么......它不应该检查一下 diff 的最后一个字符是否是\0情况又是怎样呢?

无论如何,我是否可以解决这个问题,而不必使用比较并指定长度来比较或更改我的字符串?

Edit:

std::string instruction(unparsed, 0, unparsed.find(' '));
boost::algorithm::to_lower(instruction);

for(int i = 0; i < instruction.size(); i++){
    std::cout << "create from " << (int) unparsed[i] << std::endl;
    std::cout << "instruction " <<  (int) instruction[i] << std::endl;
    std::cout << "literal " << (int) "submit"[i] << std::endl;
}

std::cout << (instruction == "submit") << std::endl;

prints

create from 83
instruction 115
literal 115
create from 117
instruction 117
literal 117
create from 98
instruction 98
literal 98
create from 77
instruction 109
literal 109
create from 105
instruction 105
literal 105
create from 116
instruction 116
literal 116
create from 0
instruction 0
literal 0

0

EDIT:

为了更清楚地了解为什么我感到困惑,我阅读了 basic_string.h 标头并看到了这一点:

/**
   *  @brief  Compare to a C string.
   *  @param s  C string to compare against.
   *  @return  Integer < 0, 0, or > 0.
   *
   *  Returns an integer < 0 if this string is ordered before @a s, 0 if
   *  their values are equivalent, or > 0 if this string is ordered after
   *  @a s.  Determines the effective length rlen of the strings to
   *  compare as the smallest of size() and the length of a string
   *  constructed from @a s.  The function then compares the two strings
   *  by calling traits::compare(data(),s,rlen).  If the result of the
   *  comparison is nonzero returns it, otherwise the shorter one is
   *  ordered first.
  */
  int
  compare(const _CharT* __s) const;

这是从操作符==调用的,所以我试图找出为什么大小差异很重要。


我不太明白你的问题可能需要更多细节,但你可以使用 c 比较,它不应该有空终止计数问题。 你可以使用:

bool same = (0 == strcmp(strLiteral, stdTypeString.c_str());

strncmp 还可用于仅比较字符数组中给定数量的字符

或者尝试修复 stdstring 的创建

您未解析的 std::string 已经很糟糕了。它已经在字符串中包含了额外的 null,因此您应该查看它是如何创建的。 就像我之前提到的,mystring[mystring.size() -1] 是最后一个字符,而不是终止 null,因此如果您像在输出中那样看到“\0”,则意味着 null 被视为字符串的一部分。

尝试追踪已解析的输入并确保 mystring[mystring.size() -1] 不是 '\0'。

要回答您的尺寸差异问题: 这两个字符串不相同,文字较短并且没有空值。

  • std::string->c_str() [S,u,b,m,i,t,\0,\0] 的内存长度 = 7,内存大小 = 8;
  • 文字 [S,u,b,m,i,t,\0] 的内存长度 = 6,内存大小 = 7;

当到达文字中的终止 null 时,Compare 停止比较,但它使用 std::string 的存储大小,即 7,看到该文字以 6 终止,但 std 的大小为 7,它会说 std 更大。

我认为如果您执行以下操作,它将返回字符串是相同的(因为它将创建一个右侧也带有额外空值的 std 字符串):

std::cout << (instruction == str("submit", _countof("submit"))) << std::endl;

PS:这是在获取 char* 并从中创建 std::string 时犯的常见错误,通常只使用数组大小​​本身,但这包括 std::string 无论如何都会添加的终止零。我相信你的输入中会发生这样的事情,如果你在任何地方添加 -1 ,一切都会按预期工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ 字符串和字符串文字比较 的相关文章

随机推荐