【问题标题】:No startswith,endswith functions in Go?Go 中没有开头、结尾的函数?
【发布时间】:2012-10-25 23:50:53
【问题描述】:

只是好奇地想知道:为什么 Go 编程语言的标准库中没有标准函数,如 startwith、endwith 等?

【问题讨论】:

    标签: string go


    【解决方案1】:

    strings 包包含 HasPrefixHasSuffix

    import "strings"
    
    startsWith := strings.HasPrefix("prefix", "pre") // true
    endsWith := strings.HasSuffix("suffix", "fix") // true
    

    play.golang.org

    【讨论】:

      【解决方案2】:

      如果你正在使用字节,你可以从字节中使用这些函数 包装:

      package main
      
      import (
         "bytes"
         "fmt"
      )
      
      func main() {
         fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
         fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
         fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
      }
      

      这将比先转换为字符串成本更低。阅读时很有用 从 HTTP 请求中输入,或从本地文件中读取。

      【讨论】:

        猜你喜欢
        • 2012-12-18
        • 2019-11-06
        • 2021-04-08
        • 2023-03-03
        • 2015-02-04
        • 2015-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多