如何从字符串的开头和结尾删除所有空格?
像这样:
"hello"
退货"hello"
"hello "
退货"hello"
" hello "
退货"hello"
" hello world "
退货"hello world"
如何从字符串的开头和结尾删除所有空格?
像这样:
"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()
which 返回一个新字符串,其中从调用它的字符串的开头和结尾删除了空格。
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[])
从当前字符串中删除数组中指定的一组字符的所有前导和尾随出现。
请看以下我从 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'