簡體   English   中英

如何從字符串的開頭或結尾刪除所有空格?

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

如何從字符串的開頭和結尾刪除所有空格?

像這樣:

"hello"返回"hello"
"hello "返回"hello"
" hello "返回"hello"
" hello world "返回"hello world"

String.Trim()返回一個字符串,該字符串等於輸入字符串,其中從開始結束修剪了所有空格

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

String.TrimStart()返回一個從頭開始修剪空格的字符串:

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

String.TrimEnd()返回一個從末尾剪掉空格的字符串:

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

沒有任何方法修改原始字符串對象。

(至少在某些實現中,如果沒有要修剪的空格,您將返回與開始時相同的字符串對象:

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

我不知道這是否由語言保證。)

看一看Trim() ,它返回一個新字符串,其中從調用它的字符串的開頭和結尾刪除了空格。

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

trimmed現在是"Hello"

使用String.Trim()函數。

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

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

使用String.Trim方法。

String.Trim()從字符串的開頭和結尾刪除所有空格。 要刪除字符串中的空格或規范化空格,請使用正則表達式。

Trim()從當前字符串中刪除所有前導和尾隨空白字符。 Trim(Char)從當前字符串中刪除Trim(Char)所有前導和尾隨實例。 Trim(Char[])從當前字符串中刪除數組中指定的一組字符的所有前導和尾隨出現。

看看我從 Microsoft 的文檔頁面引用的以下示例。

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM