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"
This question is related to
c#
string
trim
removing-whitespace
use the String.Trim()
function.
string foo = " hello ";
string bar = foo.Trim();
Console.WriteLine(bar); // writes "hello"
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.
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.
Use String.Trim
method.
Trim()
Removes all leading and trailing white-space characters from the current string.
Trim(Char)
Removes all leading and trailing instances of a character from the current string.
Trim(Char[])
Removes all leading and trailing occurrences of a set of characters specified in an array from the current string.
Look at the following example that I quoted from Microsoft's documentation page.
char[] charsToTrim = { '*', ' ', '\''};
string banner = "*** Much Ado About Nothing ***";
string result = banner.Trim(charsToTrim);
Console.WriteLine("Trimmmed\n {0}\nto\n '{1}'", banner, result);
// The example displays the following output:
// Trimmmed
// *** Much Ado About Nothing ***
// to
// 'Much Ado About Nothing'
string a = " Hello ";
string trimmed = a.Trim();
trimmed
is now "Hello"
Source: Stackoverflow.com