Coder Perfect

How do I get rid of all white space at the start or end of a string?

Problem

How can I get rid of all white space at the start and end of a string?

Like so:

“hello” yields “hello,” “hello,” “hello,” “hello,” “hello,” “hello,” “hello,” “h “hello,” “hello,” “hello,” “hello,” “hello,” “hello,” “hello,” “hello,” “hello,” “hello,” ” “Welcome to the world”

Asked by pedram

Solution #1

String. Trim() returns a string that is the same as the input string, but with all white spaces removed from the beginning and end:

"   A String   ".Trim() -> "A String"

String. TrimStart() returns a string that has all white spaces removed at the beginning:

"   A String   ".TrimStart() -> "A String   "

String. TrimEnd() returns a string that is devoid of whitespace at the end:

"   A String   ".TrimEnd() -> "   A String"

None of the methods change the string object’s original state.

(If there are no white-spaces to be trimmed, you get back the same string object you started with, at least in certain implementations:

csharp> string trimmed = a.Trim(); csharp> (object) a == (object) trimmed; returns true

I’m not sure if the language makes this possible.)

Answered by Mau

Solution #2

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

Answered by Russ Cam

Solution #3

string a = "   Hello   ";
string trimmed = a.Trim();

trimmed has been completed. “Hello”

Answered by adamse

Solution #4

make use of the String Trim() is a function that trims the length of a string

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

Console.WriteLine(bar); // writes "hello"

Answered by Adam Robinson

Solution #5

Use String.Trim method.

Answered by jwaliszko

Post is based on https://stackoverflow.com/questions/3381952/how-to-remove-all-white-space-from-the-beginning-or-end-of-a-string