How to remove all white space from the beginning o

2020-01-24 06:42发布

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"

6条回答
戒情不戒烟
2楼-- · 2020-01-24 07:19

Use String.Trim method.

查看更多
够拽才男人
3楼-- · 2020-01-24 07:22

use the String.Trim() function.

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

Console.WriteLine(bar); // writes "hello"
查看更多
ら.Afraid
4楼-- · 2020-01-24 07:29
string a = "   Hello   ";
string trimmed = a.Trim();

trimmed is now "Hello"

查看更多
迷人小祖宗
5楼-- · 2020-01-24 07:29

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.

查看更多
三岁会撩人
6楼-- · 2020-01-24 07:40

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.)

查看更多
Viruses.
7楼-- · 2020-01-24 07:42

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.

查看更多
登录 后发表回答