英文:
Appending a character code to a string
问题
我试图向字符串中添加一个空字符,但是我找不到正确的语法。
我尝试过:
s += "s += "\0"
"
和:
s += "\x00"
但是这两个都给我报错。一般来说,如何通过字符代码向字符串中添加一个字符?
英文:
I'm trying to add a null character to a string but I cannot find the right syntax for it.
I've tried:
s += "s += "\0"
"
and:
s += "\x00"
but both of these give me an error. In general, how to add a character, by character code, to a string?
答案1
得分: 7
s += "\000"
添加了空字符。Go对字符串中的转义字符有严格的限制。\0 表示你正在开始一个八进制字符编码,而Go在斜杠后面需要精确地3个八进制数字。对于空字符,你需要三个0。 \x 表示你正在开始一个十六进制字符编码,同样,你需要精确地两个十六进制数字。 \u 或 \U 需要在其后面精确地4个或8个十六进制数字。详见:http://golang.org/ref/spec#Rune_literals 完整的规范细节。
英文:
s += "\000"
adds the null character. Go is a pretty strict in what it allows for escapes in a string. \0 means you are starting an octal character code and go expects exactly 3 octal digits after the slash. You need three 0's for the null character. \x means you are starting a hex character code and again you need exactly two hex digits afterwards. \u or \U require exactly 4 and 8 hexadecimal digits after it. See: http://golang.org/ref/spec#Rune_literals For the full details from the spec.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论