Different Ways to Remove Whitespaces From Strings In Go

In this blog post, you will learn how to use the TrimSpace, TrimLeft, and TrimRight functions to remove whitespaces from a string. These functions are part of the Go strings package.

TrimSpace

To trim all whitespaces from the beginning and end of a string we use the TrimSpace function. This function takes in a string and returns a new string will the whitespaces removed.

You can run this code here on Go Playground.

TrimLeft

To trim the whitespaces at the beginning of a string we use the TrimLeft function. This function takes in two parameters a string and a cutset string and returns a new string. The cutset is the part of the string you want to remove. In our case, it will be an empty space.

You can run this code here on Go Playground.

TrimRight

To trim the whitespaces at the end of a string we use the TrimRight function. This function takes in two parameters a string and a cutset string and returns a new string. The cutset is the part of the string you want to remove. In our case, it will be an empty space.

You can run this code here on Go Playground.

Conclusion

In this blog post, you learn how to use the TrimSpace, TrimLeft, and TrimRight function to remove whitespaces from a string. You can read other blogs on the strings package here.

Resources

GitHub Source.

Harrison Brock