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
string
is not a singlerune
, it may contain multiplerunes
. You may use a simple type conversion to convert astring
to a[]runes
containing all its runes like[]rune(sample)
.The
for range
iterates over the runes of astring
, so in your exampleruneValue
is of typerune
, you may use it in yourconverter
map, e.g.:But since
rune
is an alias forint32
, printing the aboveconverter
map will print integer numbers, output will be:If you want to print characters, use the
%c
verb 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
converter
map:This outputs the same. Try this one on the Go Playground.