我想查找字节数组中包含的字符串的所有出现的索引。
func findAllOccurrences(data []byte, searches []string) map[string][]int {
var results map[string][]int
for _, search := range searches {
firstMatch = bytes.Index(data, []byte(search))
results[search] = append(results[search], firstMatch)
// How do I find subsequent the rest of the matches?
}
return results
}
查找第一个
Index()
很简单,但是如何以惯用的方式查找所有ojit_code而又不消耗不必要的内存? 最佳答案
好的,这是我的评论中的解决方案,方法是先读取LastIndex
而不是首先读取ojit_code(不确定它是否有效),但这确实行得通,您只需按相反的顺序获取索引,即可在阅读时始终对其进行修复。
package main
import (
"fmt"
"bytes"
)
func main() {
str1:= "foobarfoobarfoobarfoobarfoofoobar"
arr := make([]string, 2)
arr[0]="foo"
arr[1]="bar"
res:=findAllOccurrences([]byte(str1), arr)
fmt.Println(res)
}
func findAllOccurrences(data []byte, searches []string) map[string][]int {
results:= make(map[string][]int,0)
for _, search := range searches {
index := len(data)
tmp:=data
for true{
match := bytes.LastIndex(tmp[0:index], []byte(search))
if match==-1{
break
}else{
index=match
results[search]=append(results[search], match)
}
}
}
return results
}
希望这可以帮助! :)