如何将字符串切片转换为符文切片

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

how to convert a string slice to rune slice

问题

你可以使用以下方法将类型为[]string的数组转换为[]rune

func convertToRunes(arr []string) []rune {
    result := make([]rune, len(arr))
    for i, str := range arr {
        result[i] = []rune(str)[0]
    }
    return result
}

这个方法会遍历[]string数组中的每个字符串,然后将每个字符串转换为[]rune类型,并取第一个字符作为结果数组中的元素。这样就能将[]string转换为[]rune

英文:

how can I convert type []string to []rune?

I know you can do it like this:
[]rune(strings.Join(array,""))
but is there a better way?

答案1

得分: 5

我不想使用strings.Join(array,"")来实现这个目的,因为它会构建一个我不需要的大字符串。构建一个我不需要的大字符串既不节省空间,也可能不节省时间,这取决于输入和硬件。

所以,我会遍历字符串数组,并将每个字符串转换为一个符文切片,然后使用内置的可变参数append函数来扩展我的所有符文值的切片:

var allRunes []rune
for _, str := range array {
    allRunes = append(allRunes, []rune(str)...)
}
英文:

I would prefer not to use strings.Join(array,"") for this purpose because it builds one big new string I don't need. Making a big string I don't need is not space-efficient, and depending on input and hardware it may not be time-efficient.

So instead I would iterate through the array of string values and convert each string to a rune slice, and use the built-in variadic append function to grow my slice of all rune values:

var allRunes []rune
for _, str := range array {
    allRunes = append(allRunes, []rune(str)...)
}

huangapple
  • 本文由 发表于 2017年5月20日 20:51:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/44086087.html
匿名

发表评论

匿名网友

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

确定