How to find a character index in Golang?

If you are searching for non-ASCII characters (languages other than english) you need to use http://golang.org/x/text/search.

func SubstringIndex(str string, substr string) (int, bool) {
    m := search.New(language.English, search.IgnoreCase)
    start, _ := m.IndexString(str, substr)
    if start == -1 {
        return start, false
    }
    return start, true
}

index, found := SubstringIndex('Aarhus', 'Å');
if found {
    fmt.Println("match starts at", index);
}

Search the language.Tag structs here to find the language you wish to search with or use language.Und if you are not sure.


You can use the Index function of package strings

Playground: https://play.golang.org/p/_WaIKDWCec

package main

import "fmt"
import "strings"

func main() {
    x := "chars@arefun"

    i := strings.Index(x, "@")
    fmt.Println("Index: ", i)
    if i > -1 {
        chars := x[:i]
        arefun := x[i+1:]
        fmt.Println(chars)
        fmt.Println(arefun)
    } else {
        fmt.Println("Index not found")
        fmt.Println(x)
    }
}