为什么在字符串中任意放置null终止符会终止它呢? [英] Why doesn't the null-terminator placed arbitrarily in a string terminate it?
问题描述
空字符或空终止符( \0
)用于终止连续的字符序列。我发现在C中,我可以将字符添加到随机位置的字符串中,字符串将从该点切断。例如:
The null character or null-terminator (\0
) is to be used to terminate a contiguous sequence of characters. I find that in C, I can add the character into a string at a random position and the string will be cut off from that point. For example:
char * s = "Hello\0World";
将导致 s
等于string Hello
。但是,在JavaScript中,情况并非如此:
will result in s
being equal to the string "Hello"
. In JavaScript, however, this is not the case:
var s = "Hello\0World";
以上内容无法按预期工作。 s
将等于字符串HelloWorld
。
The above won't work as expected. s
will be equal to the string "HelloWorld"
.
为什么这不起作用?
推荐答案
JavaScript不使用NULL终止字符串,而C表示。
JavaScript does not use NULL terminated strings, while C does.
通过分别跟踪字符和长度来存储Javascript字符串,而不是试图假设NULL标记字符串的结尾。
Javascript strings are stored by keeping track of the characters and the length separately instead of trying to assume that a NULL marks the end of the string.
这篇关于为什么在字符串中任意放置null终止符会终止它呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!