Go语言中字符串的常用操作
Go语言中的字符串是不可变的字节序列,提供了丰富的操作函数和方法。以下是字符串的常用操作:## 基本操作1. 字符串长度 go s := "hello" length := len(s) // 5
2. 字符串连接 go s1 := "hello" s2 := "world" s3 := s1 + " " + s2 // "hello world"
3. 字符串比较 go s1 := "abc" s2 := "def" if s1 == s2 { // 相等比较 } if s1 < s2 { // 字典序比较 }
## 字符串索引和切片1. 访问字符(字节) go s := "hello" b := s[1] // 'e' (类型是byte)
2. 切片 go s := "hello, world" sub := s[0:5] // "hello"
## 字符串转换1. 与[]byte转换 go s := "hello" b := []byte(s) // 转为字节切片 s2 := string(b) // 转回字符串
2. 与[]rune转换(处理UTF-8) go s := "你好" r := []rune(s) // [20320, 22909] s2 := string(r)
## 字符串查找1. Contains检查包含 go strings.Contains("hello", "ell") // true
2. Index查找位置 go strings.Index("hello", "l") // 2 strings.LastIndex("hello", "l") // 3
3. 前缀/后缀检查 go strings.HasPrefix("hello", "he") // true strings.HasSuffix("hello", "lo") // true
## 字符串修改1. Replace替换 go strings.Replace("hello", "l", "L", 2) // "heLLo"
2. ToUpper/ToLower大小写转换 go strings.ToUpper("hello") // "HELLO" strings.ToLower("HELLO") // "hello"
3. Trim修剪 go strings.Trim(" hello ", " ") // "hello" strings.TrimLeft("hello", "he") // "llo" strings.TrimRight("hello", "lo") // "he"
## 字符串分割与合并1. Split分割 go parts := strings.Split("a,b,c", ",") // ["a", "b", "c"]
2. Join合并 go s := strings.Join([]string{"a", "b", "c"}, ",") // "a,b,c"
3. Fields按空格分割 go words := strings.Fields("a b c") // ["a", "b", "c"]
## 字符串格式化1. Sprintf格式化 go s := fmt.Sprintf("%s %d", "hello", 123) // "hello 123"
2. Builder高效构建 go var builder strings.Builder builder.WriteString("hello") builder.WriteString(" ") builder.WriteString("world") result := builder.String() // "hello world"
## UTF-8相关操作1. Rune计数 go utf8.RuneCountInString("你好") // 2
2. Rune遍历 go for i, r := range "你好" { fmt.Printf("%d: %c\n", i, r) }
这些操作涵盖了Go语言中字符串处理的大部分常见需求。对于更复杂的字符串处理,可以结合正则表达式(regexp包)或第三方库使用。