【问题标题】:Is there a Go function that works like linux cut?有没有像 linux cut 一样工作的 Go 函数?
【发布时间】:2020-03-24 05:16:03
【问题描述】:

这可能是一个非常基本的问题,但在查看了字符串包文档后,我无法找到答案。

基本上,我想做的只是相当于:

echo "hello world" | cut -d" " -f2

【问题讨论】:

    标签: string go split cut


    【解决方案1】:
    echo "hello world" | cut -d" " -f2
    

    这使用空格作为分隔符拆分字符串"hello world",并仅选择第二部分(1-indexed)。

    在 Go for spitting 中有 strings.Split() 返回一个切片,您可以根据需要对其进行索引或切片。

    s := "hello world"
    
    fmt.Println(strings.Split(s, " ")[1])
    

    这输出相同。在Go Playground 上试试。如果不能保证输入有 2 个部分,则上述索引 ([1]) 可能会出现恐慌。在这样做之前检查切片的长度。

    【讨论】:

      【解决方案2】:

      strings.Split() 函数在指定的子字符串处拆分字符串。

      还有函数Fields(s string) []stringFieldsFunc(s string, f func(rune) bool) []string

      前者在空格处分割字符串,后者使用给定的函数来确定字符串是否必须被分割。

      SplitFields 的区别在于Fields 将多个连续的空格视为一个分割位置。 strings.Fields(" foo bar baz ")) 产生["foo" "bar" "baz"]strings.Split(" foo bar baz ", " ") 产生["" "" "foo" "bar" "" "baz" "" "" ""]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-18
        • 1970-01-01
        • 2022-12-29
        • 2010-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多