go 提供了多种查找字符串的方法: 1. index 函数查找子字符串的第一个出现位置,如果没有则返回 -1。 2. indexbyte 函数查找单个字符(字节)的第一个出现位置。 3. lastindex 函数从字符串末尾开始查找子字符串的最后一个出现位置。 4. contains 函数检查子字符串是否存在,存在返回 true,不存在返回 false。 5. hasprefix 和 hassuffix 函数检查字符串是否以子字符串开头或结尾,符合返回 true,否则返回 false。
如何在 Go 中查找字符串
Go 提供了多种方法来查找字符串:
1. 使用 Index
Index 函数返回指定子字符串在字符串中的第一个出现位置,如果没有匹配项,则返回 -1。
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)
}
}
2. 使用 IndexByte
IndexByte 函数类似于 Index,但它适用于单个字符(字节)。
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)
}
}
3. 使用 LastIndex
LastIndex 函数与 Index 类似,但它从字符串的末尾开始搜索。
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)
}
}
4. 使用 Contains
Contains 函数检查字符串中是否包含指定的子字符串,如果包含,则返回 true,否则返回 false。
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'")
}
}
5. 使用 HasPrefix 和 HasSuffix
HasPrefix 和 HasSuffix 函数检查字符串是否以指定的子字符串开头或结尾,如果符合,则返回 true,否则返回 false。
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!'")
}
}