Here is my code snippet:
var converter = map[rune]rune {//some data}
sample := "⌘こんにちは"
var tmp string
for _, runeValue := range sample {
fmt.Printf("%+q", runeValue)
tmp = fmt.Sprintf("%+q", runeValue)
}
The output of fmt.Printf("%+q", runeValue) is:
'\u2318'
'\u3053'
'\u3093'
'\u306b'
'\u3061'
'\u306f'
These value are literally rune but as the return type of Sprintf is string, I cannot use it in my map which is [rune]rune.
I was wondering how can I convert string to rune, or in other words how can I handle this problem?
A
stringis not a singlerune, it may contain multiplerunes. You may use a simple type conversion to convert astringto a[]runescontaining all its runes like[]rune(sample).The
for rangeiterates over the runes of astring, so in your exampleruneValueis of typerune, you may use it in yourconvertermap, e.g.:But since
runeis an alias forint32, printing the aboveconvertermap will print integer numbers, output will be:If you want to print characters, use the
%cverb offmt.Printf():Which will output:
Try the examples on the Go Playground.
If you want to replace (switch) certain runes in a
string, use thestrings.Map()function, for example:Which outputs (try it on the Go Playground):
If you want the replacements defined by a
convertermap:This outputs the same. Try this one on the Go Playground.