6

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

2 Answers 2

13

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
}
Sign up to request clarification or add additional context in comments.

Comments

6

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 { 
    ...
}

1 Comment

This would return n - 1 if the string wasn't found. play.golang.org/p/N5McWNY8t0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.