跳转到主内容
websoft网络软件专家 - 深耕网络技术,打造实用软件!

【Go 每日一库】strings

文章目录 【Go 每日一库】strings 1. 为什么需要 strings 包?

2. 常用方法速览与示例 ✅ 2.1 判断前缀/后缀:`HasPrefix` / `HasSuffix` ✅ 2.2 查找子串:`Contains` / `Index` / `LastIndex` ✅ 2.3 字符串替换:`Replace` / `ReplaceAll` ✅ 2.4 分割字符串:`Split` / `Fields` ✅ 2.5 拼接字符串:`Join` ✅ 2.6 大小写转换:`ToLower` / `ToUpper` / `ToTitle` ✅ 2.7 去除首尾字符:`Trim` / `TrimPrefix` / `TrimSuffix` ✅ 2.8 重复字符串:`Repeat` ✅ 2.9 判断是否相等(忽略大小写):`EqualFold` ✅ 2.10 高级分割:`SplitN` / `SplitAfter` 3. 性能小贴士 4. 实战小练习 5. 总结 【Go 每日一库】strings 📌 一句话总结 :

strings

是 Go 标准库中最常用、最实用的字符串操作包之一,提供了大量用于查找、分割、替换、比较等操作的函数,无需正则也能轻松应对大多数字符串处理场景。

1. 为什么需要 strings 包?

在 Go 语言中,字符串是不可变的字节序列(UTF-8 编码)。

虽然可以直接使用

+

拼接或

[]byte

转换进行操作,但面对复杂的文本处理需求(如判断前缀、按分隔符切分、大小写转换等),手动实现既繁琐又容易出错。

strings

包封装了大量高效、安全、易用的函数,让你专注于业务逻辑,而不是底层细节。

2. 常用方法速览与示例 我们按照使用频率和功能分类,介绍最常用的 10 个方法,并附上可直接运行的代码示例。

✅ 2.1 判断前缀/后缀:

HasPrefix

/

HasSuffix package main

import ( "fmt" "strings" )

func main() { s := "hello.go" fmt.Println(strings.HasPrefix(s, "hello")) // true fmt.Println(strings.HasSuffix(s, ".go")) // true }

💡 应用场景:文件类型判断、URL 路由匹配等。

✅ 2.2 查找子串:

Contains

/

Index

/

LastIndex s := "Go is awesome! Go rocks!"

fmt.Println(strings.Contains(s, "awesome")) // true fmt.Println(strings.Index(s, "Go")) // 0(首次出现位置) fmt.Println(strings.LastIndex(s, "Go")) // 15(最后一次出现位置)

⚠️ 注意:

Index

返回的是字节索引(不是 rune 索引),对纯 ASCII 安全;若含中文需谨慎。

✅ 2.3 字符串替换:

Replace

/

ReplaceAll s := "apple, apple, banana"

// 替换前 n 个(n=1) fmt.Println(strings.Replace(s, "apple", "orange", 1)) // 输出: orange, apple, banana

// 全部替换 fmt.Println(strings.ReplaceAll(s, "apple", "orange")) // 输出: orange, orange, banana

🔁

ReplaceAll(s, old, new)

等价于

Replace(s, old, new, -1)

✅ 2.4 分割字符串:

Split

/

Fields // 按指定分隔符切分

parts := strings.Split("a,b,c", ",") fmt.Println(parts) // [a b c]

// 按空白字符(空格、制表符、换行等)自动切分 words := strings.Fields(" Go\t\n is great ") fmt.Println(words) // [Go is great]

🧹

Fields

会自动忽略多余空白,非常适合解析用户输入。

✅ 2.5 拼接字符串:

Join list := []string{"Go", "Rust", "Python"}

result := strings.Join(list, " | ") fmt.Println(result) // Go | Rust | Python

🚀 比多次

+

拼接更高效(内部使用

strings.Builder

优化)。

✅ 2.6 大小写转换:

ToLower

/

ToUpper

/

ToTitle s := "Hello World"

fmt.Println(strings.ToLower(s)) // hello world fmt.Println(strings.ToUpper(s)) // HELLO WORLD fmt.Println(strings.ToTitle(s)) // HELLO WORLD(注意:ToTitle ≠ Title)

🌍 注意:这些函数基于 Unicode 规范,支持多语言(如德语 ß → SS)。

✅ 2.7 去除首尾字符:

Trim

/

TrimPrefix

/

TrimSuffix s := "!!Hello Go!!"

fmt.Println(strings.Trim(s, "!")) // Hello Go fmt.Println(strings.TrimPrefix(s, "!!")) // Hello Go!! fmt.Println(strings.TrimSuffix(s, "!!")) // !!Hello Go

🧼

Trim

可传入任意字符集合(如

"\n\t "

),常用于清理用户输入。

✅ 2.8 重复字符串:

Repeat fmt.Println(strings.Repeat("Go ", 3)) // Go Go Go

🎯 小技巧:可用于生成分隔线

strings.Repeat("-", 50)

✅ 2.9 判断是否相等(忽略大小写):

EqualFold fmt.Println(strings.EqualFold("GO", "go")) // true

🔐 比先转大写再比较更高效、更安全(避免 locale 问题)。

✅ 2.10 高级分割:

SplitN

/

SplitAfter s := "a=b=c=d"

// 最多切分成 3 段 fmt.Println(strings.SplitN(s, "=", 3)) // [a b c=d]

// 保留分隔符在每段末尾 fmt.Println(strings.SplitAfter(s, "=")) // [a= b= c= d]

🛠️ 适用于解析键值对、日志等结构化文本。

3. 性能小贴士

strings

包的函数大多经过高度优化, 优先使用标准库而非手写循环 。

对于大量拼接操作,考虑使用

strings.Builder

(虽不在

strings

包内,但密切相关)。

所有函数都 不修改原字符串 (Go 字符串不可变),而是返回新字符串。

4. 实战小练习 题目 :写一个函数,将形如

"user@example.com"

的邮箱地址拆分为用户名和域名。

func parseEmail(email string) (user, domain string) {

parts := strings.Split(email, "@") if len(parts) != 2 { return "", "" } return parts[0], parts[1] }

// 测试 user, domain := parseEmail("alice@gmail.com") fmt.Println(user, domain) // alice gmail.com

5. 总结 功能推荐函数 判断开头/结尾HasPrefix,HasSuffix查找Contains,Index替换ReplaceAll分割Split,Fields拼接Join清理Trim,TrimPrefix大小写ToLower,ToUpper

strings

包虽小,却是 Go 开发者的日常利器。

掌握它,能让你的代码更简洁、更健壮、更高效!

相关文章