C# 删除变量中的空格
我的变量看起来像:
name = "Lola "; // notice the whitespace
如何删除末尾的空格,只留下“Lola”?
谢谢大家,但是 .Trim() 对我不起作用。
我从文件中读取文本,如果有帮助的话。
My variable looks like:
name = "Lola "; // notice the whitespace
How can I delete the whitespace at the end to leave me with just "Lola"?
Thank you all, but .Trim() don't work to me.
I read the text from a file, if that is any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
使用
Trim()
。
use
Trim()
.如果空格始终位于字符串的末尾,请使用:
如果空格也可能位于字符串的开头,则使用:
If the space will always be at the end of the string, use:
If the space may also be at the beginning, then use:
Trim
不会更改字符串,它会创建一个新的修剪副本。这就是为什么看起来name.Trim();
没有做任何事情——你正在丢弃结果。相反,使用
name = name.Trim();
作为 ICR 建议。Trim
doesn't change the string, it creates a new trimmed copy. That is why it seems likename.Trim();
isn't doing anything -- you are throwing away the results.Instead, use
name = name.Trim();
as ICR suggests.答案是
.Trim()
。请注意,由于字符串是不可变的,因此您必须分配操作的结果:The answer is
.Trim()
. Note that since strings are immutable, you have to assign the result of the operation:查看 string.Trim()
http://msdn.microsoft.com/en -us/library/t97s7bs3.aspx
Check out string.Trim()
http://msdn.microsoft.com/en-us/library/t97s7bs3.aspx
使用
Trim()
方法。Use the
Trim()
method.只需用于
删除字符串中的所有空格即可;
从字符串末尾删除空格
从字符串开头删除空格
Just use
to remove all spaces from your string;
to remove spaces from the end of your string
to remove spaces from the start of your string
使用修剪()。
所以你只能得到“Lola”
use Trim().
So u can get only "Lola"
或者这就是你想要做的?
Or is this what you meant to do?
如果您想删除字符串中任何位置的所有空格,可以使用
Replace()
If you wanted to remove all spaces anywhere in the string, you could use
Replace()