How to find a character index in Golang?

mobu picture mobu · Dec 29, 2013 · Viewed 58.2k times · Source

I'm trying to find "@" string character in Go but I cannot find a way to do it. I know how to index characters like "HELLO[1]" which would output "E". However I'm trying to find index number of the found char.

In Python I'd do it in following way:

x = "chars@arefun"
split = x.find("@")
chars = x[:split]
arefun = x[split+1:]

>>>print split
5
>>>print chars
chars
>>>print arefun
arefun

So chars would return "chars" and arefun would return "arefun" while using "@" delimeter. I've been trying to find solution for hours and I cannot seem to find proper way to do it in Golang.

Answer

siritinga picture siritinga · Dec 29, 2013

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)
    }
}