在 Go 语言 里,strings 包就是专门用来查找、判断、处理字符串的。下面按常见场景给你一个速查表。
strings.Containsimport "strings"
s := "hello world"
fmt.Println(strings.Contains(s, "world")) // true
fmt.Println(strings.Contains(s, "go")) // false
strings.Index(第一次出现)s := "hello world"
fmt.Println(strings.Index(s, "world")) // 6
fmt.Println(strings.Index(s, "go")) // -1
strings.LastIndex(最后一次出现)s := "hello world world"
fmt.Println(strings.LastIndex(s, "world")) // 12
strings.HasPrefixs := "https://example.com"
fmt.Println(strings.HasPrefix(s, "https")) // true
strings.HasSuffixs := "test.txt"
fmt.Println(strings.HasSuffix(s, ".txt")) // true
strings 本身没有“返回子串”的函数,但你可以结合 Index 手动取:
s := "hello world"
i := strings.Index(s, "world")
if i != -1 {
fmt.Println(s[i : i+len("world")]) // world
}
strings.Counts := "go go go"
fmt.Println(strings.Count(s, "go")) // 3
strings.Replace / strings.ReplaceAlls := "hello world"
fmt.Println(strings.ReplaceAll(s, "world", "golang"))
// hello golang
Go 没有内置,但常用做法是转成小写:
s := "Hello World"
sub := "world"
if strings.Contains(strings.ToLower(s), strings.ToLower(sub)) {
fmt.Println("found")
}
❌ 不能直接用 == 判断子串
s == "world" // 错,这是判断整个字符串
✅ 用 strings.Contains
| 需求 | 函数 |
|---|---|
| 是否包含 | strings.Contains |
| 第一次位置 | strings.Index |
| 最后一次位置 | strings.LastIndex |
| 以…开头 | strings.HasPrefix |
| 以…结尾 | strings.HasSuffix |
| 替换 | strings.ReplaceAll |
| 出现次数 | strings.Count |
如果你想查的是 Linux 命令行里的 strings 工具,或者 正则查找字符串,也可以告诉我,我可以单独讲。