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?
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.
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With