英文:
How can I get Chinese first letter(Pinyin) by using Go language?
问题
我这里有一个问题。我需要使用golang获取一个中文词的拼音。例如:
我想从中文词“世界”中获取字母“S”,除了“世”之外。
Go语言能自动完成这个任务吗?
英文:
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?
答案1
得分: 4
使用utf8包,你可以这样做:
func firstLetter(s string) string {
_, size := utf8.DecodeRuneInString(s)
return s[:size]
}
或者
func firstLetter(s string) string {
for _, l := range s {
return string(l)
}
return ""
}
你不能使用s[0]
,因为它会返回多字节符的第一个字节。
英文:
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.
答案2
得分: 1
使用 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('界'))
}
如果你有一个包含中文字符的字符串,你可以遍历字符串来获取字符的 rune。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论