Go语言中字符串的常用操作

Go语言中字符串的常用操作

Go语言中的字符串是不可变的字节序列,提供了丰富的操作函数和方法。以下是字符串的常用操作:## 基本操作1. 字符串长度 go s := "hello" length := len(s) // 52. 字符串连接 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") // true2. Index查找位置 go strings.Index("hello", "l") // 2 strings.LastIndex("hello", "l") // 33. 前缀/后缀检查 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("你好") // 22. Rune遍历 go for i, r := range "你好" { fmt.Printf("%d: %c\n", i, r) }这些操作涵盖了Go语言中字符串处理的大部分常见需求。对于更复杂的字符串处理,可以结合正则表达式(regexp包)或第三方库使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值