How to remove redundant spaces/whitespace from a string in Golang?

后端 未结 5 2052
借酒劲吻你
借酒劲吻你 2021-02-02 12:44

I was wondering how to remove:

  • All leading/trailing whitespace or new-line characters, null characters, etc.
  • Any redundant spaces within
5条回答
  •  清酒与你
    2021-02-02 13:27

    Use regexp for this.

    func main() {
        data := []byte("   Hello,   World !   ")
        re := regexp.MustCompile("  +")
        replaced := re.ReplaceAll(bytes.TrimSpace(data), []byte(" "))
        fmt.Println(string(replaced))
        // Hello, World !
    }
    

    In order to also trim newlines and null characters, you can use the bytes.Trim(src []byte, cutset string) function instead of bytes.TrimSpace

提交回复
热议问题