所以我想简单地做一个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;
这是从操作符==调用的,所以我试图找出为什么大小差异很重要。