Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim leading and trailing white spaces of a string?

Tags:

go

Which is the effective way to trim the leading and trailing white spaces of string variable in Go?

like image 600
Alex Mathew Avatar asked Mar 27 '14 12:03

Alex Mathew


People also ask

How do you cut leading and trailing spaces from a string?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

How do you trim white spaces from a string?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)

Does trim remove leading and trailing spaces?

TRIM function - remove extra spaces in Excel You use the TRIM function in Excel removes extra spaces from text. It deletes all leading, trailing and in-between spaces except for a single space character between words.

Which function is used to remove leading and trailing whitespace of a string?

strip(): returns a new string after removing any leading and trailing whitespaces including tabs (\t). rstrip(): returns a new string with trailing whitespace removed.


2 Answers

strings.TrimSpace(s)

For example,

package main  import (     "fmt"     "strings" )  func main() {     s := "\t Hello, World\n "     fmt.Printf("%d %q\n", len(s), s)     t := strings.TrimSpace(s)     fmt.Printf("%d %q\n", len(t), t) } 

Output:

16 "\t Hello, World\n " 12 "Hello, World" 
like image 54
peterSO Avatar answered Sep 23 '22 10:09

peterSO


There's a bunch of functions to trim strings in go.

See them there : Trim

Here's an example, adapted from the documentation, removing leading and trailing white spaces :

fmt.Printf("[%q]", strings.Trim(" Achtung  ", " ")) 
like image 29
Denys Séguret Avatar answered Sep 24 '22 10:09

Denys Séguret