tags:

views:

174

answers:

7

How automatically remove all white space start or end in a string like:

"hello" return "hello"
"hello " return "hello"
" hello " return "hello"
" hello world " return "hello world"

regards

+4  A: 

take a look at Trim() which returns a new string with whitespace removed from the beginning and end of the string it is called on.

Russ Cam
+1  A: 

use the String.Trim() function.

string foo = "   hello ";
string bar = foo.Trim();

Console.WriteLine(bar); // writes "hello"
Adam Robinson
+2  A: 
string a = "   Hello   ";
string trimmed = a.Trim();

trimmed is now "Hello"

adamse
+2  A: 

String.Trim() removes all whitespace from the beginning and end of a string. To remove whitespace inside a string, or normalize whitespace, use a Regular Expression.

tdammers
+2  A: 

Use String.Trim method.

Jarek Waliszko
A: 

Try

string myString = " Hello World ";
myString = myString.TrimStart().TrimEnd();

Ash Burlaczenko
`Trim()` does the same as `TrimStart().TrimEnd()` but without multiple string instance creation
abatishchev
Ok, my apologies. For some reason i had it in my head that trim() only stripped the right hand side.
Ash Burlaczenko
+4  A: 

String.Trim() will trim all spaces from start and end of a string:

"   A String   " -> "A String"

String.TrimStart() will trim all spaces from the start of a string:

"   A String   " -> "A String   "

String.TrimEnd() will trim all spaces from the end of a string:

"   A String   " -> "   A String"
Mau
thank you thanks other guys .
pedram