How to remove all white space from the beginning or end of a string?
Solution 1
String.Trim()
returns a string which equals the input string with all white-spaces trimmed from start and end:
" A String ".Trim() -> "A String"
String.TrimStart()
returns a string with white-spaces trimmed from the start:
" A String ".TrimStart() -> "A String "
String.TrimEnd()
returns a string with white-spaces trimmed from the end:
" A String ".TrimEnd() -> " A String"
None of the methods modify the original string object.
(In some implementations at least, if there are no white-spaces to be trimmed, you get back the same string object you started with:
csharp> string a = "a";
csharp> string trimmed = a.Trim();
csharp> (object) a == (object) trimmed;
returns true
I don't know whether this is guaranteed by the language.)
Solution 2
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.
Solution 3
string a = " Hello ";
string trimmed = a.Trim();
trimmed
is now "Hello"
Solution 4
use the String.Trim()
function.
string foo = " hello ";
string bar = foo.Trim();
Console.WriteLine(bar); // writes "hello"
Solution 5
Use String.Trim
method.
Related videos on Youtube
pedram
Updated on December 12, 2020Comments
-
pedram over 3 years
How can I remove all white space from the beginning and end of a string?
Like so:
"hello"
returns"hello"
"hello "
returns"hello"
" hello "
returns"hello"
" hello world "
returns"hello world"
-
Hi-Angel over 8 years⁺¹ for the MS definition of whitespace. I met a weird behavior that
.TrimEnd()
doesn't work (for non-breaking space character), but in the end is just that the character not listed in documentation. -
Admin almost 8 yearsThere are numerous ways to trim strings, and quite a few are bench-marked. Still, I like .Trim() as being the quickest to write and easiest to read.
-
Nash Carp over 6 yearsMaybe it is usefull to know this: If you have multiply lines like in a TextArea. And you press the enter key, you get something like:
" A String \r\n "
.Trim()
does recognize this as a space too. -
huha over 5 years@NashCarp: That´s because \r and \n are also whitespace characters