drduh44480 2018-09-04 22:13
浏览 425
已采纳

获取字符串数组中每个字符串的第一个字符

I am new to golang and I am trying to obtain the first character of a string in an array of strings. It seems like it would be easy, but I don't know how to approach it. Here is what I have done thus far:

package main

import (
    "fmt"
    "os"
    "strings"
)

func acronym(s string) (acr string) {

    // TODO: Your code here
    var arrayOfStrings []string
    arrayOfStrings = strings.Split(s, " ") //split string s into an array of strings based on space delimeter " "
    for _, str := range arrayOfStrings {
        fmt.Println(str)
    }
    return acr
}

func main() {
    s := "Pan Galactic Gargle Blaster"
    if len(os.Args) > 1 {
        s = strings.Join(os.Args, " ")
    }
    fmt.Println(acronym(s))
}

I want the resulting string to be PGGB I am a bit stuck as I have only looped through the array of strings, but i can't think of something like in java where one has the method/function charAt(). Thanks!

  • 写回答

1条回答 默认 最新

  • dtcmadj31951 2018-09-04 22:32
    关注

    something like in java where one has the method/function charAt()

    In go, strings are immutable byte sequences with the contents encoded in UTF-8. The string representation is roughly, but not exactly, equivalent to a []byte slice (the distinction is unimportant for the purposes of this answer).

    There are various library approaches you can use in go:

    • If your string is guaranteed to consist of ASCII or other single-byte characters, you can simply index the string to recover bytes at arbitrary positions. Indexing the string at the ith position will return the byte at that location. In your case, this would be str[0].

    • If you specifically seek the first character, rather than the first byte, and your string may contain higher byte order Unicode code points, you need to decode the string as Unicode accordingly. The unicode/utf8 package provides support for this. Code like the following in your loop in acronym will properly decode the first UTF-8-encoded rune of each string str for you:

    for _, str := range arrayOfStrings {
        r, _ := utf8.DecodeRuneInString(str)
        acr = acr + string(r)
    }
    

    You should note the documentation for the DecodeRuneInString method around error conditions:

    If s is empty it returns (RuneError, 0). Otherwise, if the encoding is invalid, it returns (RuneError, 1). Both are impossible results for correct, non-empty UTF-8.

    If either condition is possible in your system, ensure you add appropriate error handling logic to check the return result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题