我如何从字符串的开头和结尾删除所有的空格?
像这样:
"hello"
返回 "hello"
"hello "
返回 "hello"
" hello "
返回 "hello"
" hello world "
返回 "hello world"
```javascript str.trim(); ```
这将返回一个新字符串,其中包含原始字符串中除去开头和结尾空格后的部分。
我如何从字符串的开头和结尾删除所有的空格?
像这样:
"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;
返回 true
我不知道语言是否保证了这一点。)
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'
.TrimEnd()
不起作用(对于非断行空格字符),但最终只是因为该字符未列在文档中。 - Hi-Angel" A String \r\n "
。.Trim()
也会将其识别为一个空格。 - Nash Carp