使用strings.Contains判断子串存在,strings.Index获取位置,strings.Replace按次数替换,strings.NewReplacer批量替换,高效处理字符串操作。

在Golang中实现字符串查找与替换非常简单,主要依赖标准库 strings 包提供的函数。这些函数高效、易用,适用于大多数常见场景。
使用 strings.Contains 进行字符串查找
如果只是判断一个字符串是否包含另一个子串,可以使用 strings.Contains:
func Contains(s, substr string) bool示例:
found := strings.Contains("hello world", "world")
fmt.Println(found) // 输出: true
立即学习“go语言免费学习笔记(深入)”;
这个函数返回布尔值,适合做条件判断。
使用 strings.Index 查找子串位置
若需要知道子串在原字符串中的起始索引,使用 strings.Index:
func Index(s, substr string) int示例:
pos := strings.Index("hello world", "world")
fmt.Println(pos) // 输出: 6
如果没有找到,返回 -1。
使用 strings.Replace 进行字符串替换
最常用的替换函数是 strings.Replace,其定义如下:
func Replace(s, old, new string, n int) string参数说明:
- s:原始字符串
- old:要被替换的子串
- new:用来替换的新字符串
- n:最多替换几次;-1 表示全部替换
示例:
result := strings.Replace("hello world world", "world", "Go", 1)
fmt.Println(result) // 输出: hello Go world
resultAll := strings.Replace("hello world world", "world", "Go", -1)
fmt.Println(resultAll) // 输出: hello Go Go
使用 strings.Replacer 进行多次替换
如果需要一次性替换多个不同的子串,推荐使用 strings.NewReplacer,它更高效:
replacer := strings.NewReplacer("A", "X", "B", "Y", "C", "Z")
result := replacer.Replace("ABC and ABC")
fmt.Println(result) // 输出: XYZ and XYZ
注意:替换规则是按顺序应用的,且会全部替换。
基本上就这些。根据需求选择合适的函数即可。对于简单查找用 Contains 或 Index,替换用 Replace,批量替换用 Replacer。不复杂但容易忽略细节,比如 Replace 的第四个参数控制替换次数。










