Go 提供了多种查找字符串的方法: 1. Index 函数查找子字符串的第一个出现位置,如果没有则返回 -1。 2. IndexByte 函数查找单个字符(字节)的第一个出现位置。 3. LastIndex 函数从字符串末尾开始查找子字符串的最后一个出现位置。 4. Contains 函数检查子字符串是否存在,存在返回 true,不存在返回 false。 5. HasPrefix 和 HasSuffix 函数检查字符串是否以子字符串开头或结尾,符合返回 true,否则返回 false。

如何在 Go 中查找字符串
Go 提供了多种方法来查找字符串:
1. 使用 Index
Index 函数返回指定子字符串在字符串中的第一个出现位置,如果没有匹配项,则返回 -1。
立即学习“go语言免费学习笔记(深入)”;
<code class="go">package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, Go!"
index := strings.Index(str, "Go")
if index == -1 {
fmt.Println("Not found")
} else {
fmt.Println("Found at index:", index)
}
}</code>2. 使用 IndexByte
IndexByte 函数类似于 Index,但它适用于单个字符(字节)。
<code class="go">package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, Go!"
index := strings.IndexByte(str, 'G')
if index == -1 {
fmt.Println("Not found")
} else {
fmt.Println("Found at index:", index)
}
}</code>3. 使用 LastIndex
LastIndex 函数与 Index 类似,但它从字符串的末尾开始搜索。
<code class="go">package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, Go Go!"
index := strings.LastIndex(str, "Go")
if index == -1 {
fmt.Println("Not found")
} else {
fmt.Println("Found at index:", index)
}
}</code>4. 使用 Contains
Contains 函数检查字符串中是否包含指定的子字符串,如果包含,则返回 true,否则返回 false。
<code class="go">package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, Go!"
contains := strings.Contains(str, "Go")
if contains {
fmt.Println("Yes, it contains 'Go'")
} else {
fmt.Println("No, it doesn't contain 'Go'")
}
}</code>5. 使用 HasPrefix 和 HasSuffix
HasPrefix 和 HasSuffix 函数检查字符串是否以指定的子字符串开头或结尾,如果符合,则返回 true,否则返回 false。
<code class="go">package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, Go!"
hasPrefix := strings.HasPrefix(str, "Hello")
hasSuffix := strings.HasSuffix(str, "Go!")
if hasPrefix {
fmt.Println("Yes, it starts with 'Hello'")
} else {
fmt.Println("No, it doesn't start with 'Hello'")
}
if hasSuffix {
fmt.Println("Yes, it ends with 'Go!'")
} else {
fmt.Println("No, it doesn't end with 'Go!'")
}
}</code>以上就是golang怎么查找字符串的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号