字符串操作(长度、拼接、子串)

字符串是不可变的字节序列,常用于文本处理。

1. 字符串长度

使用 len 获取字符串长度(字节数):

s := "Hello"
fmt.Println(len(s))  // 输出:5

`

注意:中文字符占多个字节。

2. 字符串拼接

使用 + 操作符拼接字符串:

s1 := "Hello"
s2 := "World"
s := s1 + " " + s2
fmt.Println(s)  // 输出:Hello World

也可以使用 strings.Join 拼接字符串切片:

import "strings"

words := []string{"Go", "is", "fun"}
sentence := strings.Join(words, " ")
fmt.Println(sentence)  // 输出:Go is fun

3. 子串提取

通过切片操作提取子串:

s := "Hello World"
sub := s[0:5]  // "Hello"

字符串操作是日常开发基础,掌握常用方法便于高效处理文本数据。