I got a question here.I need to get the pinyin of a Chinese word using golang.For example:
What I want to get from Chinese "世界" is letter "S" except "世".
Can go language do this automatically?
Use github.com/mozillazg/go-pinyin
package main
import (
"fmt"
"github.com/mozillazg/go-pinyin"
)
var a = pinyin.NewArgs()
func FirstLetterOfPinYin(r rune) string {
result := pinyin.Pinyin(string(r), a)
return string(result[0][0][0])
}
func main() {
fmt.Println(FirstLetterOfPinYin('世'))
fmt.Println(FirstLetterOfPinYin('界'))
}
If you have string of Chinese characters, you can range the string to get rune of the chars.
Using the utf8 package you can do something like:
func firstLetter(s string) string {
_, size := utf8.DecodeRuneInString(s)
return s[:size]
}
or
func firstLetter(s string) string {
for _, l := range s {
return string(l)
}
return ""
}
You can't do s[0]
since that would return the first byte of the multi-byte rune.