drduh44480
drduh44480
2018-09-04 22:13

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

  • slice
已采纳

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 dtcmadj31951 3年前

    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.

    点赞 评论 复制链接分享