Golang : Extract unicode string from another unicode string example
Problem:
You have a string with unicode (UTF-8) characters and you want to extract part of the string by using character indexing. However, the output result is weird. What is the correct way to extract unicode (UTF-8) characters from a string?
Solution:
Wrap the string with []rune
, then index the characters and finally the convert the rune bytes to string.
Here you go!
package main
import "fmt"
func main() {
// wrong way
fmt.Println("fuß is german language for foot"[1])
// wrong way
fmt.Println(string("fuß is german language for foot"[1]))
// correct way
fmt.Println(string([]rune("fuß is german language for foot")[0:3]))
// correct way
fmt.Println(string([]rune("腳 is chinese language for foot")[0:1]))
}
Output:
117
u
fuß
腳
alternatively, you can use the strings.SplitN()
function as well.
package main
import (
"fmt"
"strings"
)
func main() {
str := "腳 is chinese language for foot"
// extract each word from str
parts := strings.SplitN(str, " ", -1)
fmt.Println(parts[0])
fmt.Println(parts[1])
fmt.Println(parts[2])
fmt.Println(parts[3])
fmt.Println(parts[4])
fmt.Println(parts[5])
}
Output:
腳
is
chinese
language
for
foot
Happy coding!
References:
https://golang.org/ref/spec#Index_expressions
https://www.socketloop.com/tutorials/golang-get-first-few-and-last-few-characters-from-string
https://www.socketloop.com/tutorials/golang-extract-sub-strings
See also : Golang : Get first few and last few characters from string
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.7k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+8.8k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+5.9k Golang : Grab news article text and use NLP to get each paragraph's sentences
+11.5k Golang : Surveillance with web camera and OpenCV
+86.9k Golang : How to convert character to ASCII and back
+10.2k Golang : Wait and sync.WaitGroup example
+8.2k Golang : Number guessing game with user input verification example
+10.2k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+9.6k Golang : Detect number of active displays and the display's resolution
+5.7k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+8.4k Android Studio : Import third-party library or package into Gradle Scripts
+17.9k Golang : How to log each HTTP request to your web server?