十五、Go 语言 – 字符串

十五、Go 语言 – 字符串

在Go编程中广泛使用的字符串是只读字节片。在Go编程语言中,字符串是。Go平台提供了各种库来操作字符串。- unicode - regexp -字符串

Creating Strings

创建字符串最直接的方法是写入

1
var greeting = "Hello world!"

每当在代码中遇到字符串字面值时,编译器就会创建一个字符串对象,在本例中,它的值为“Hello world!”

字符串字面值包含一个有效的UTF-8序列,称为符文。String保存任意字节。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import "fmt"

func main() {
var greeting = "Hello world!"

fmt.Printf("normal string: ")
fmt.Printf("%s", greeting)
fmt.Printf("\n")
fmt.Printf("hex bytes: ")

for i := 0; i < len(greeting); i++ {
fmt.Printf("%x ", greeting[i])
}
fmt.Printf("\n")

const sampleText = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98"
/*q flag escapes unprintable characters, with + flag it escapses non-ascii
characters as well to make output unambigous
*/
fmt.Printf("quoted string: ")
fmt.Printf("%+q", sampleText)
fmt.Printf("\n")
}

This would produce the following result −

1
2
3
normal string: Hello world!
hex bytes: 48 65 6c 6c 6f 20 77 6f 72 6c 64 21
quoted string: "\xbd\xb2=\xbc \u2318"

注意−字符串字面值是不可变的,因此一旦创建了字符串字面值就不能被更改。

String Length

Len (str)方法返回字符串字面值中包含的字节数。

1
2
3
4
5
6
7
8
9
10
package main

import "fmt"

func main() {
var greeting = "Hello world!"

fmt.Printf("String Length is: ")
fmt.Println(len(greeting))
}

这将产生以下结果-

1
String Length is : 12

Concatenating Strings

strings包包含一个方法join,用于连接多个字符串

1
strings.Join(sample, " ")

联接数组的元素以创建单个字符串。第二个参数是位于数组元素之间的分隔符。

让我们看看下面的例子

1
2
3
4
5
6
7
8
package main

import ("fmt" "math" )"fmt" "strings")

func main() {
greetings := []string{"Hello","world!"}
fmt.Println(strings.Join(greetings, " "))
}

这将产生以下结果-

1
Hello world!