golang -- 字符串操做

相關包有strings, strconvpython


  • 判斷是否以某字符串打頭/結尾
    strings.HasPrefix(s string, prefix string) bool => 對應python的str.startswith 
    strings.HasSuffix(s string, suffix string) bool => 對應python的str.endswith
    spa

  • 字符串分割
    strings.Split(s string, sep string) []string => 對應python的str.splitcode

  • 返回子串索引
    strings.Index(s string, sub string) int => 對應python的str.index
    strings.LastIndex 最後一個匹配索引索引

  • 字符串鏈接
    strings.Join(a []string, sep string) string =>對應python的str.join字符串

  • 字符串替換
    strings.Replace(s, old, new string, n int) string =>對應python的str.replace
    string

  • 轉爲大寫/小寫
    strings.ToUpper(s string) string
    strings.ToLower
    對應python的str.upper,str.lowerit

  • 子串個數io

    strings.Count(s string, sep string) intast

    對應python的 str.countclass

  • Partition
    python的str.partition在解析包時候很好用,這裏封裝一個

    func Partition(s string, sep string) (head string, retSep string, tail string) {
        // Partition(s, sep) -> (head, sep, tail)
        index := strings.Index(s, sep)
        if index == -1 {
            head = s
            retSep = ""
            tail = ""
        } else {
            head = s[:index]
            retSep = sep
            tail = s[len(head)+len(sep):]
        }
        return
    }

    Partition使用

// 包格式 頭(xy) + 數據體 + 尾 (..xy...)
// ...
_, header, msg := Partition(data, "xy")
if header == "" {
    // 沒有頭(xy)丟包. (也有可能粘包分包致使 "...x", 最後一個(注意是一個)字符變成了x, 這時要把前面的包丟棄,只保留一個x)
} else {
    // do
}
相關文章
相關標籤/搜索