"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Efficiently Strip All Whitespace from a String in Go?

How to Efficiently Strip All Whitespace from a String in Go?

Posted on 2025-02-07
Browse:885

How to Efficiently Strip All Whitespace from a String in Go?

Stripping Whitespace Efficiently in Go: Finding the Optimal Solution

When working with strings in Go, ensuring efficient handling of whitespace removal is crucial. This question explores the optimal approach to strip all whitespace from a string.

Question:

How can I expeditiously strip all whitespace from an arbitrary string in Go? I've experimented with chaining the strings.Fields() and strings.Join() functions, but I suspect there's a more efficient method.

Response:

A straightforward and efficient solution is to utilize the strings.ReplaceAll() function:

randomString := "  hello      this is a test"
fmt.Println(strings.ReplaceAll(randomString, " ", ""))

// Output:
// hellothisisatest

By employing strings.ReplaceAll(), you can replace all occurrences of the specified whitespace character (in this case, " ") with an empty string. This approach is more concise and performant compared to chaining multiple functions.

Playground:

[Go Playground Demonstration](https://go.dev/play/p/m4OHzJ5FaCo)

Note:

It's important to note that this method removes a specific type of whitespace character. If your input string contains different types of whitespace (e.g., tabs, newlines), you may need to execute multiple strings.ReplaceAll() calls to address each type individually.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3