Golang : Convert(cast) string to rune and back to string example
Tutorial on how how to convert a string to rune type and back to string. Dealing with rune can be confusing sometimes because single quotes and double quotes can have different meaning in Golang. This example code below is pretty straightforward and ... is self explanatory.
Here you go!
package main
import (
"fmt"
"regexp/syntax"
)
func main() {
str := []rune("beta") // use rune slice
acharacter := rune('a') // use single quote, instead of double quote
onerune := rune('吃')
fmt.Printf("%v \n", string(str)) // convert back to string
fmt.Printf("%v \n", string(acharacter)) // convert back to string
fmt.Printf("%v \n", string(onerune)) // convert back to string
// there are times when accessing str is not acceptable because
// it is a slice. Therefore, you just have to reference the first
// element
// for example :
ok := syntax.IsWordChar(str[0]) // won't work without [0]
fmt.Printf("%v is a word ? : %v \n", string(str), ok)
}
Output :
beta
a
吃
beta is a word ? : true
See also : Golang : convert rune to integer value
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
+4.2k Python : Convert(cast) bytes to string example
+24.6k Golang : Get executable name behind process ID example
+12.9k Golang : Get uploaded file name or access uploaded files
+9.4k Golang : ISO8601 Duration Parser example
+10.6k Golang : Convert decimal number(integer) to IPv4 address
+13.9k Golang : Find location by IP address and display with Google Map
+21k Golang : Repeat a character by multiple of x factor
+9.8k Golang : Generate random elements without repetition or duplicate
+11.1k Golang : Add ASCII art to command line application launching process
+5.1k Golang : Extract XML attribute data with attr field tag example
+23.7k Golang : Convert long hexadecimal with strconv.ParseUint example
+16.6k Golang : Get all upper case or lower case characters from string example