为什么在 std 字符串中间设置 null 没有任何效果
考虑到
#include <string>
#include <iostream>
int main()
{
/*
hello
5
hel
3
*/
char a[] = "hello";
std::cout << a << std::endl;
std::cout << strlen(a) << std::endl;
a[3] = 0;
std::cout << a << std::endl;
std::cout << strlen(a) << std::endl;
/*
hello
5
hel o
5
*/
std::string b = "hello";
std::cout << b << std::endl;
std::cout << b.length() << std::endl;
b[3] = 0;
std::cout << b << std::endl;
std::cout << b.length() << std::endl;
getchar();
}
我期望 std::string 的行为与 char 数组 a 相同。就是这样,在字符串中间插入空字符,将“终止”字符串。然而,事实并非如此。我的期望是错误的吗?
Consider
#include <string>
#include <iostream>
int main()
{
/*
hello
5
hel
3
*/
char a[] = "hello";
std::cout << a << std::endl;
std::cout << strlen(a) << std::endl;
a[3] = 0;
std::cout << a << std::endl;
std::cout << strlen(a) << std::endl;
/*
hello
5
hel o
5
*/
std::string b = "hello";
std::cout << b << std::endl;
std::cout << b.length() << std::endl;
b[3] = 0;
std::cout << b << std::endl;
std::cout << b.length() << std::endl;
getchar();
}
I expect std::string
will behave identical to char
array a. That's it, insert null character in the middle of the string, will "terminate" the string. However, it is not the case. Is my expectation wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
std::string
与通常的 C 字符串不同,它可以毫无问题地包含嵌入的 NUL 字符。但是,如果您这样做,您会发现如果您使用.c_str()
函数返回const char *
,字符串会提前终止。A
std::string
is not like a usual C string, and can contain embedded NUL characters without problems. However, if you do this you will notice the string is prematurely terminated if you use the.c_str()
function to return aconst char *
.否 -
std::string
不像 C“字符串”那样以 NUL 结尾; std::string 独立记录其长度。No -
std::string
s are not NUL-terminated like C "strings"; the std::string records its length independently.@Lou 是对的:不要这样做。相反,请执行以下操作:
@Lou is right: don't do that. Instead, do this:
是的,你的期望是错误的。
std::string
意味着与C字符串不同(例如不一定存储在连续的内存/数组中)。要复制第一部分的行为,请尝试 std::cout << b.c_str() 而不是
std::cout << b。
Yes, your expectation is wrong.
std::string
is meant to be different from C strings (e.g. not necessarily stored in consecutive memory / an array).To duplicate the first section's behavior, try
std::cout << b.c_str()
instead ofstd::cout << b
.我希望 std::string 的行为与 char 数组 a 相同。为什么
?文档中任何地方都没有与 std::string 有关的内容说明它是这样做的。
我的建议是,停止将 C++ 视为 C 加一些东西。
I expect std::string will behave identical to char array a.
Why? Nothing in the documentation, anywhere, having to do with std::string says it does this.
My suggestion, stop treating like C++ as C plus some stuff.