如何将 []string 转换为 []rune?

huangapple go评论112阅读模式
英文:

How to convert []string to []rune

问题

我尝试编写一个程序,该程序接受一个短语作为输入,并使用单词的首字母来构成缩写。
所以,"Today I learned" → "TIL" 或者 "Высшее учебное заведение" → "ВУЗ"。
我不知道如何处理西里尔字母,所以我的逻辑是获取字符串的字段并将其转换为符文,但问题是如何进行转换。

s := "Высшее учебное заведение"
arr := strings.Fields(s)
var runes []rune
for i := range arr {
runes = append(runes, rune(arr[i][0]))
}
fmt.Println(runes) // 这里我得到的是字节 [208 209 208],但期望得到的是符文

英文:

I try to write a program that takes as input a phrase and makes up an abbreviation using the first letters of the words.
So, "Today I learned" → "TIL" or "Высшее учебное заведение" → "ВУЗ".
I dont know how to deal with cyrillic alphabet, so my logic now is to get fields of string and convert it to runes, but the question is how to convert

  1. s := "Высшее учебное заведение"
  2. arr := strings.Fields(s)
  3. var runes []rune
  4. for i := range arr {
  5. runes = append(runes, rune(arr[i][0]))
  6. }
  7. fmt.Println(runes) // here I get bytes [208 209 208] but expect to get runes

答案1

得分: 1

你可以轻松地将字符串转换为[]rune类型:

  1. r := []rune("ABc€")

如果你想获取字符的Unicode码点,你可以在打印时使用%U格式:

  1. fmt.Printf("%U\n", r)
英文:

You can convert a string to []rune easily:

  1. r := []rune("ABc€")

If you want to get runes, you should use %U format in print:

  1. fmt.Printf("%U\n", r)

huangapple
  • 本文由 发表于 2022年8月6日 23:11:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/73260925.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定