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

后端 未结 5 2059
借酒劲吻你
借酒劲吻你 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

    You can get quite far just using the strings package as strings.Fields does most of the work for you:

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func standardizeSpaces(s string) string {
        return strings.Join(strings.Fields(s), " ")
    }
    
    func main() {
        tests := []string{" Hello,   World  ! ", "Hello,\tWorld ! ", " \t\n\t Hello,\tWorld\n!\n\t"}
        for _, test := range tests {
            fmt.Println(standardizeSpaces(test))
        }
    }
    // "Hello, World !"
    // "Hello, World !"
    // "Hello, World !"
    

提交回复
热议问题