您的位置:首页 > 编程语言 > Go语言

Go语言学习之字符串(The way to go)

2017-03-19 22:58 1046 查看
生命不止,继续Go go go. 今天与大家分享golang中的字符串。

跟其他很多编程语言一样,字符串也是go中的内建类型。

字符串是这样声明的:

type stringStruct struct {
str *byte
len int
}


这里需要强调一下:byte 和 uint8 是一样一样的。

字符串是不可变的字节序列,这里跟c++有一点点区别的。

下面是go中字符串的简单应用:

package main

import (
"fmt"
"strings"
)

const World = "world"

func main() {
var hello = "hello"

// 104 is the ascii code of char 'h'
fmt.Println(hello[0]) // 104

// strings are immutable
// hello[0] = 'H' // error: cannot assign to hello[0]

// all variables are addressable
fmt.Println(&hello)

// bytes in string are not addressable
// fmt.Println(&hello[0]) // error: cannot take the address of hello[0]

// string concatenation
var helloWorld = hello + " " + World
helloWorld += "!"
fmt.Println(helloWorld) // hello world!

// comparison
var hello2 = helloWorld[:len(hello)]
fmt.Println(hello == hello2)    // true
fmt.Println(hello > helloWorld) // false

// get string length
fmt.Println(len(hello), len(helloWorld)) // 5 12

// strings util functions
fmt.Println(strings.HasPrefix(helloWorld, hello)) // true
}


按下表访问

不可变

字符串有地址,但是不能获取元素的地址,例如&str[1]

通过+进行字符串连接

可对字符串进行比较

通过len获取字符串的长度

strings是go为我们提供的字符串包

编码

go中字符串默以utf-8编码存储,但是字面量里允许十六进制、八进制和utf编码格式。

package main

import "fmt"

func main() {
str := "保健\x61\142\u0042"
fmt.Printf("%s\n", str)
fmt.Printf("%x, len: %d\n", str, len(str))
}


输出:

保健abB

e4bf9de581a5616242, len: 9

原始字符串

python中有原始字符串,c++11也引入里原始字符串,在go中也有原始字符串,使用`表示,且看代码:

package main

import "fmt"

func main() {
str := `保健\x61\142\u0042`
fmt.Printf("%s\n", str)
fmt.Printf("%x, len: %d\n", str, len(str))
}


输出:

保健\x61\142\u0042

e4bf9de581a55c7836315c3134325c7530303432, len: 20

转换



byte rune两种方式

for-range will iterate the runes, instead of bytes, in a string (or speaking more accurately, for-range will treat the underlying bytes of a string as a Unicode code point sequence and iterate the code points). Illegal UTF-8 bytes will be interpreted as rune value 0xfffd.

package main

import "fmt"

func main() {
s := "éक्षिaπ汉字"
for i, rn := range s {
fmt.Printf("%d: 0x%xd %s \n", i, rn, string(rn))
}
}


输出:

0: 0x65d e

1: 0x301d ́

3: 0x915d क

6: 0x94dd ्

9: 0x937d ष

12: 0x93fd ि

15: 0x61d a

16: 0x3c0d π

18: 0x6c49d 汉

21: 0x5b57d 字

这里需要注意的是,i可能不连续
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: