简体   繁体   English

如何从字符串的开头或结尾删除所有空格?

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

How can I remove all white space from the beginning and end of a string?如何从字符串的开头和结尾删除所有空格?

Like so:像这样:

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

String.Trim() returns a string which equals the input string with all white-spaces trimmed from start and end:String.Trim()返回一个字符串,该字符串等于输入字符串,其中从开始结束修剪了所有空格

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

String.TrimStart() returns a string with white-spaces trimmed from the start: String.TrimStart()返回一个从头开始修剪空格的字符串:

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

String.TrimEnd() returns a string with white-spaces trimmed from the end: String.TrimEnd()返回一个从末尾剪掉空格的字符串:

"   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.)我不知道这是否由语言保证。)

看一看Trim() ,它返回一个新字符串,其中从调用它的字符串的开头和结尾删除了空格。

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

trimmed is now "Hello" trimmed现在是"Hello"

use the String.Trim() function.使用String.Trim()函数。

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

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

使用String.Trim方法。

String.Trim() removes all whitespace from the beginning and end of a string. String.Trim()从字符串的开头和结尾删除所有空格。 To remove whitespace inside a string, or normalize whitespace, use a Regular Expression.要删除字符串中的空格或规范化空格,请使用正则表达式。

Trim() Removes all leading and trailing white-space characters from the current string. Trim()从当前字符串中删除所有前导和尾随空白字符。 Trim(Char) Removes all leading and trailing instances of a character from the current string. Trim(Char)从当前字符串中删除Trim(Char)所有前导和尾随实例。 Trim(Char[]) Removes all leading and trailing occurrences of a set of characters specified in an array from the current string. Trim(Char[])从当前字符串中删除数组中指定的一组字符的所有前导和尾随出现。

Look at the following example that I quoted from Microsoft's documentation page.看看我从 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