如何删除字符串开头或结尾的所有空格? [英] How to remove all white space from the beginning or end of a string?

查看:305
本文介绍了如何删除字符串开头或结尾的所有空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I remove all white space from the beginning and end of a string?

就像这样:

hello 返回 hello

hello 返回你好

你好 返回你好

你好世界 返回你好世界

"hello" returns "hello"
"hello " returns "hello"
" hello " returns "hello"
" hello world " returns "hello world"

推荐答案

String.Trim() 返回的字符串等于输入字符串,其中所有空白从开始 end:

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

String.TrimStart()返回从头开始修剪空格的字符串:

String.TrimStart() returns a string with white-spaces trimmed from the start:

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

String.TrimEnd()返回从末尾开始修剪空格的字符串:

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>字符串a = a;
csharp>字符串trimped = a.Trim();
csharp>(对象)a ==(对象)修剪;
返回true

我不知道这种语言是否可以保证。)

I don't know whether this is guaranteed by the language.)

这篇关于如何删除字符串开头或结尾的所有空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆