所以我试图简单地做一个std::string == "string-literal"
可以正常工作的方法,除了我正在创建我的字符串
std::string str(strCreateFrom, 0, strCreateFrom.find(' '));
并找到返回string::npos
现在这两个都包含字符串"submit"
但是==
返回false,现在我已经将其缩小到尺寸是“不同”的事实,即使它们确实不是。str.size()
是 7 和strlen("submit")
6。这就是为什么==
失败,我认为是,但我不明白为什么......它不应该检查 diff 的最后一个字符是否\0
与这种情况下的情况一样吗?
无论如何我可以解决这个问题而不必使用比较并指定长度来比较或更改我的字符串?
编辑:
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;
这是从 operator== 调用的,所以我试图找出为什么大小差异很重要。