末尾没有空字符的 std::string
是否有效,是否可以这样获取?:
std::string str = "Hello World";
str.resize(str.size() - 1);
对于那些好奇的人:
我有一个第 3 方函数获取一个字符串并迭代字符(使用迭代器)。不幸的是,这个函数有问题(因为它是一个开发版本)并且不能处理空字符。我没有其他签名可供选择,我不能修改功能(正如我所说,第 3 方,我们不想 fork )同时我不想重新发明轮子。据我所知,该函数应该在没有空字符的情况下按预期工作,所以我至少想试一试。
迭代是这样进行的:
bool nextChar(CharIntType& c)
{
if (_it == _end) return false;
c = *_it;
++_it;
return true;
}
其中 _it
被初始化为 std::string::begin()
和 _end
被初始化为 std::string::结束()
最佳答案
在 C++11 之前,std::string 不需要包含尾随 nul,直到您调用 c_str()
。
http://en.cppreference.com/w/cpp/string/basic_string/data
std::string::data()
Returns pointer to the underlying array serving as character storage. The pointer is such that the range [data(); data() + size()) is valid and the values in it correspond to the values stored in the string.
The returned array is not required to be null-terminated. If empty() returns true, the pointer is a non-null pointer that should not be dereferenced. (until c++11)
The returned array is null-terminated, that is, data() and c_str() perform the same function. If empty() returns true, the pointer points to a single null character. (since c++11)
从这里我们可以确认 std::string::size 不包括任何 nul 终止符,并且 std::string::begin() 和 std::string::end() 描述了你实际的范围寻找。
我们还可以通过 std::string::back() 不返回 nul 字符这一简单事实来确定这一点。
#include <iostream>
#include <string>
int main() {
std::string s("hello, world");
std::cout << "s.front = " << s.front() << " s.back = " << s.back() << '\n';
return 0;
}
关于c++ - std::string 没有空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21244842/