2018-09-04 22:13
浏览 347


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 (

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 {
    return acr

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

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.

    点赞 评论

相关推荐 更多相似问题