英文:
Golang string end character
问题
我是一个Golang的新手,所以我正在尝试一些算法,但是我遇到了一个小问题。
在Java中,如果要在字符数组中插入一个结束字符串,可以这样做:
String str = "Mr John Smith ";
char[] arr = str.toCharArray();
arr[12] = 'String str = "Mr John Smith ";
char[] arr = str.toCharArray();
arr[12] = '\0';
';
但是在Golang中,我尝试了以下代码:
str := []byte("Mr John Smith ")
str[12] = 'str := []byte("Mr John Smith ")
str[12] = '\0'
'
但是这段代码没有起作用。
英文:
I'm a newbie in Golang, so I'm playing with some algorithms and i have a little problem.
In java for insert an end string in char array I can do like this:
String str = "Mr John Smith ";
char[] arr = str.toCharArray();
arr[12] = 'String str = "Mr John Smith ";
char[] arr = str.toCharArray();
arr[12] = '\0';
';
But in Golang I'm trying like this:
str := []byte("Mr John Smith ")
str[12] = 'str := []byte("Mr John Smith ")
str[12] = '\0'
'
But this code didn't work
答案1
得分: 6
这不是一个有效的表示零值的符文字面量语法。你可以使用十六进制转义序列:
str[12] = '\x00'
如果你真的需要一个八进制值,它需要三个数字:
str[12] = 'str[12] = '\000'
0'
或者直接赋值字面量 0
:
str[12] = 0
你可以在规范中查看有效的符文字面量转义序列:https://golang.org/ref/spec#Rune_literals
英文:
That's not a valid syntax for a rune literal with a 0 value. You can use the hex escape sequence
str[12] = '\x00'
If you really need an octal value, it requires 3 digits
str[12] = 'str[12] = '\000'
0'
Or just assign a literal 0
str[12] = 0
You can see the valid rune literal escape sequences in the specification: https://golang.org/ref/spec#Rune_literals
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论