c++ - std::string 没有空字符

标签 c++ string

末尾没有空字符的 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;
}

http://ideone.com/nUX0AB

关于c++ - std::string 没有空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21244842/

相关文章:

python - 将相对日期字符串转换为绝对日期

ios - 在 Swift 中将 CamelCase 字符串分隔为空格分隔的单词

python - 删除 Pandas 中的标点符号

c++ - 带有可选解析器的 Boost.Qi 编译器错误

c++ - 使用 boost::beast 异步处理流式 HTTP

c++ - 如何以编程方式获取 DLL 或 EXE 文件的版本?

c++ - 如何通用地编写隐藏结构的属性? (C++ 的设计/实现)

c++ - 从字符串数组转换为 char* const

c - malloc 之后出现段错误 char**

c++ - mmorpg中的c多线程