Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position in characters of a substring in Go

Tags:

string

go

rune

How can I know the position of a substring in a string, in characteres (or runes) instead of bytes?

strings.Index(s, sub) will give the position in bytes. When using Unicode, it doesn't match the position in runes: http://play.golang.org/p/DnlFjPaD2j

func main() {
    s := "áéíóúÁÉÍÓÚ"
    fmt.Println(strings.Index(s, "ÍÓ"))
}

Result: 14. Expected: 7

Of course, I could convert s and sub to []rune and look for the subslice manually, but is there a better way to do it?

Related to this, to get the first n characters of a string I'm doing this: string([]rune(s)[:n]). Is it the best way?

like image 519
siritinga Avatar asked Feb 16 '14 09:02

siritinga


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.

How do I find a character in a string by position?

Java String indexOf() Method The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do I get the index of a string in Go?

To get the index of a substring in a string in Go programming, call Index function of strings package, and pass the string and substring as arguments to this function. strings is the package. Index is the function name. str is the string in which we have to find the index of substr .

What is position in a string?

A string position is a point within a string. It can be compared to an integer (which it is derived from), but it also acts as a pointer within a string so that the preceding and following text can be extracted.


1 Answers

You can do it like this, after importing the unicode/utf8 package:

func main() {
    s := "áéíóúÁÉÍÓÚ"
    i := strings.Index(s, "ÍÓ")
    fmt.Println(utf8.RuneCountInString(s[:i]))
}

http://play.golang.org/p/Etszu3rbY3

like image 108
Agis Avatar answered Sep 20 '22 20:09

Agis