Strip all whitespace from a string

前端 未结 3 1691
心在旅途
心在旅途 2020-12-29 01:31

What is the fastest way to strip all whitespace from some arbitrary string in Go.

I am chaining two function from the string package:

response = stri         


        
3条回答
  •  执念已碎
    2020-12-29 02:24

    From rosettacode.org :

    You can find this kind of function :

    func stripChars(str, chr string) string {
        return strings.Map(func(r rune) rune {
            if strings.IndexRune(chr, r) < 0 {
                return r
            }
            return -1
        }, str)
    }
    

    So, simply replacing chr by " " here should be enough to do the trick and remove the whitespaces.

    Beware that there are other kind of whitespaces defined by unicode (like line break, nbsp, ...), and you might also want to get rid of those (especially if you're working with external data you don't really have control over)

    This would be done that way:

    func stripSpaces(str string) string {
        return strings.Map(func(r rune) rune {
            if unicode.IsSpace(r) {
                // if the character is a space, drop it
                return -1
            }
            // else keep it in the string
            return r
        }, str)
    }
    

    Then simply apply to your string. Hope it works, didn't test.

提交回复
热议问题