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

C++ string and string literal comparison

本文关键字:字符串 比较 文字 C++      更新时间:2023-10-16

所以我试图简单地做一个可以正常工作的std::string == "string-literal",除了我正在创建我的字符串

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

并找到返回string::npos现在这两个都包含字符串"submit"但是==返回 false,现在我已将其缩小到大小"不同"的事实,即使它们实际上不是。 str.size()是 7,strlen("submit")是 6。这就是==失败的原因吗,我想是,但我不明白为什么......它不应该检查 DIF 的最后一个字符是否像在这种情况下那样吗?

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

编辑:

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;

指纹

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

编辑:

为了进一步澄清为什么我感到困惑,我阅读了 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;

这是从运算符==调用的,所以我试图找出为什么大小dif很重要。

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

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

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

或者尝试修复标准字符串的创建

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

尝试追溯解析的输入,并继续确保 mystring[mystring.size(( -1] 不是 '\0'。

要回答您的尺码差异问题,请执行以下操作:这两个字符串不同,文字较短,没有空值。

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

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

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

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

PS:这是在获取字符*并从中制作std::string时出现的常见错误,通常只使用数组大小本身,但其中包括std::string无论如何都会添加的终止零。我相信这样的事情正在某处发生在您的输入中,如果您在哪里添加 -1,一切都会按预期工作。