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

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

    Avoiding to use time wasting regexp or external library
    I've choose to use plain golang instead of regexp, cause there are special character that are not ASCII in every language.

    Go Golang!

    func RemoveDoubleWhiteSpace(str string) string {
        var b strings.Builder
        b.Grow(len(str))
        for i := range str {
            if !(str[i] == 32 && (i+1 < len(str) && str[i+1] == 32)) {
                b.WriteRune(rune(str[i]))
            }
        }
        return b.String()
    }
    

    And the related test

    func TestRemoveDoubleWhiteSpace(t *testing.T) {
        data := []string{`  test`, `test  `, `te  st`}
        for _, item := range data {
            str := RemoveDoubleWhiteSpace(item)
            t.Log("Data ->|"+item+"|Found: |"+str+"| Len: ", len(str))
            if len(str) != 5 {
                t.Fail()
            }
        }
    }
    

提交回复
热议问题