在指定的字符串中查找子字符串的索引,同时指定起始索引。

huangapple go评论141阅读模式
英文:

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

问题

我知道有strings.Indexstrings.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 { 
    ...
}

huangapple
  • 本文由 发表于 2014年9月15日 03:15:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/25837030.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定