Golang字符串的结束字符

huangapple go评论101阅读模式
英文:

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

huangapple
  • 本文由 发表于 2017年3月4日 01:29:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/42585085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定