Find index in a string using startIndex

I'm new to find and find the index of a string in a string, but I want to pass in the starting index.

I know there are .Index and strings.LastIndex, but they just find the first and last. Is there any function I can use where I can specify the starting 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

      

+3


source to share


2 answers


This is 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
}

      

+3


source


No, but it might be easier to apply strings.Index on a piece of string

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

      



See example (for the case where no string is found, see OneOfOne's answer ), but commented by Dewy Broto , one can simply test it with ' if

' including a simple statement
:
(also called ' if

' with an initialization statement
)

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

      

+5


source







All Articles