Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a character index in Golang?

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.

like image 1000
mobu Avatar asked Dec 29 '13 16:12

mobu


People also ask

How do you access characters in a string in go?

Accessing the individual bytes of a string We print the bytes in the string 'Hello String' by looping through the string using len() method. the len() method returns the number of bytes in the string, we then use the returned number to loop through the string and access the bytes at each index.

What is Golang index?

Index() Function in Golang is used to get the first instance of a specified substring. If the substring is not found, then this method will return -1. Syntax: func Index(str, sbstr string) int.

How do you read a character in a string in Golang?

To access the string's first character, we can use the slice expression [] in Go. In the example above, we have passed [0:1] to the slice expression. so it starts the extraction at position 0 and ends at position 1 (which is excluded). Note: The above syntax works on ASCII Characters.


2 Answers

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)     } } 
like image 133
siritinga Avatar answered Sep 27 '22 22:09

siritinga


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.

like image 24
Xeoncross Avatar answered Sep 27 '22 22:09

Xeoncross