英文:
Find index of a substring in a string, with start index specified
问题
我知道有strings.Index
和strings.LastIndex
函数,但它们只能找到第一个和最后一个匹配的位置。是否有任何函数可以让我指定起始索引?就像我示例中的最后一行一样。
示例:
s := "go gopher, go"
fmt.Println(strings.Index(s, "go")) // 位置 0
fmt.Println(strings.LastIndex(s, "go")) // 位置 11
fmt.Println(strings.Index(s, "go", 1)) // 位置 3 - 从索引 1 开始查找 "go"
英文:
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
得分: 12
这是一个令人讨厌的疏忽,你必须创建自己的函数。
类似这样:
func indexAt(s, sep string, n int) int {
idx := strings.Index(s[n:], sep)
if idx > -1 {
idx += n
}
return idx
}
英文:
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
得分: 5
不,但是在字符串的切片上应用strings.Index可能更简单。
strings.Index(s[1:], "go")+1
strings.Index(s[n:], "go")+n
参见示例(如果未找到字符串,请参见OneOfOne的答案),但是正如Dewy Broto的评论所指出的,可以通过一个包含简单语句的if语句进行测试:
(也称为带有初始化语句的if语句)
if i := strings.Index(s[n:], sep) + n; i >= n {
...
}
英文:
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 {
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论