How to remove all white space from the beginning or end of a string?

非 Y 不嫁゛ 提交于 2019-11-26 05:23:59

问题


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\"


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




回答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.




回答3:


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

trimmed is now "Hello"




回答4:


use the String.Trim() function.

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

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



回答5:


Use String.Trim method.




回答6:


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.



来源:https://stackoverflow.com/questions/3381952/how-to-remove-all-white-space-from-the-beginning-or-end-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!