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 写uniapp时遇到的问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流