温馨提示×

如何用strings查字符串

小樊
32
2026-08-17 11:11:09
栏目: 编程语言

Go 语言 里,strings 包就是专门用来查找、判断、处理字符串的。下面按常见场景给你一个速查表。


一、判断是否包含某个字符串

strings.Contains

import "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.HasPrefix

s := "https://example.com"
fmt.Println(strings.HasPrefix(s, "https")) // true

strings.HasSuffix

s := "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.Count

s := "go go go"
fmt.Println(strings.Count(s, "go")) // 3

六、查找并替换

strings.Replace / strings.ReplaceAll

s := "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 工具,或者 正则查找字符串,也可以告诉我,我可以单独讲。

0