Golang返回子串的所有索引

在编程中,我们经常需要在一个字符串中查找特定的子串,并获取其在原字符串中的所有位置。在Golang中,我们可以使用strings包提供的函数来实现这一功能。本文将详细介绍如何在Golang中返回一个字符串中所有指定子串的索引。
strings.Index和strings.LastIndex函数
在Golang中,strings包提供了两个用于查找子串的函数:Index和LastIndex。其中,Index函数返回子串在字符串中第一次出现的位置,LastIndex函数返回子串在字符串中最后一次出现的位置。
package main
import (
"fmt"
"strings"
)
func main() {
str := "hello world hello"
substr := "hello"
index := strings.Index(str, substr)
lastIndex := strings.LastIndex(str, substr)
fmt.Printf("Index of %s: %d\n", substr, index)
fmt.Printf("Last Index of %s: %d\n", substr, lastIndex)
}
运行结果:
Index of hello: 0
Last Index of hello: 12
在示例代码中,我们定义了一个字符串str和一个子串substr,然后使用Index和LastIndex函数分别找到子串在字符串中第一次和最后一次出现的位置。最后输出为子串的索引。
返回所有子串的索引
如果我们需要返回一个字符串中所有指定子串的索引位置,我们可以使用一个循环来逐个查找子串的位置并存储到一个切片中。以下是一个示例代码:
package main
import (
"fmt"
"strings"
)
func findAllIndex(s, substr string) []int {
indices := []int{}
index := -1
for {
index = strings.Index(s[index+1:], substr)
if index == -1 {
break
}
indices = append(indices, index+index+1)
}
return indices
}
func main() {
str := "hello world hello"
substr := "hello"
indices := findAllIndex(str, substr)
fmt.Printf("All Index of %s: %v\n", substr, indices)
}
运行结果:
All Index of hello: [0 12]
在示例代码中,我们定义了一个函数findAllIndex,它接受一个字符串和一个子串作为参数,返回一个包含所有子串索引的切片。在函数中,我们利用一个循环来查找子串出现的位置,并将其存储到切片中。最后在main函数中调用findAllIndex函数并输出。
结语
通过使用Golang中的strings包提供的函数,我们可以很方便地返回一个字符串中所有指定子串的索引位置。
极客笔记