Find index of a substring in a string, with start index specified

▼魔方 西西 提交于 2021-02-16 14:16:12

问题


I know there is strings.Index and strings.LastIndex, but they just find the first and last. Is there any function I can use, where I can specify the start index? Something like the last line in my example.

Example:

s := "go gopher, go"
fmt.Println(strings.Index(s, "go")) // Position 0
fmt.Println(strings.LastIndex(s, "go")) // Postion 11
fmt.Println(strings.Index(s, "go", 1)) // Position 3 - Start looking for "go" begining at index 1

回答1:


It's an annoying oversight, you have to create your own function.

Something like:

func indexAt(s, sep string, n int) int {
    idx := strings.Index(s[n:], sep)
    if idx > -1 {
        idx += n
    }
    return idx
}



回答2:


No, but it might be simpler to apply strings.Index on a slice of the string

strings.Index(s[1:], "go")+1
strings.Index(s[n:], "go")+n

See example (for the case where the string isn't found, see OneOfOne's answer), but, as commented by Dewy Broto, one can simply test it with a 'if' statement including a simple statement:
(also called 'if' with an initialization statement)

if i := strings.Index(s[n:], sep) + n; i >= n { 
    ...
}


来源:https://stackoverflow.com/questions/25837030/find-index-of-a-substring-in-a-string-with-start-index-specified

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!