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

在Golang中实现字符串查找与替换非常简单,主要依赖标准库 strings 包提供的函数。这些函数高效、易用,适用于大多数常见场景。
如果只是判断一个字符串是否包含另一个子串,可以使用 strings.Contains:
func Contains(s, substr string) bool示例:
found := strings.Contains("hello world", "world")
fmt.Println(found) // 输出: true
立即学习“go语言免费学习笔记(深入)”;
这个函数返回布尔值,适合做条件判断。
若需要知道子串在原字符串中的起始索引,使用 strings.Index:
func Index(s, substr string) int示例:
pos := strings.Index("hello world", "world")
fmt.Println(pos) // 输出: 6
如果没有找到,返回 -1。
最常用的替换函数是 strings.Replace,其定义如下:
func Replace(s, old, new string, n int) string参数说明:
示例:
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.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 的第四个参数控制替换次数。
以上就是如何在Golang中实现字符串查找与替换的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号