使用 C# 使用字符数组修剪字符串
当您在字符串对象上使用 Trim() 方法时,您可以向其传递一个字符数组,它将从字符串中删除这些字符,例如
string strDOB = "1975-12-23 ";
MessageBox.Show(strDOB.Substring(2).Trim("- ".ToCharArray()));
:是“75-12-23”而不是预期的结果:“751223”,这是为什么?
奖励问题: 与这一行相比,哪一个会产生更多的开销(它的作用完全相同):
strDOB.Substring(2).Trim().Replace("-", "");
When you use the Trim() method on a string object, you can pass an array of characters to it and it will remove those characters from your string, e.g:
string strDOB = "1975-12-23 ";
MessageBox.Show(strDOB.Substring(2).Trim("- ".ToCharArray()));
This results is "75-12-23" instead of the expected result: "751223", why is this?
Bonus question:
Which one would have more overhead compared to this line (it does exactly the same thing):
strDOB.Substring(2).Trim().Replace("-", "");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为trim函数只修剪字符串末尾的字符。
如果您想在各处消除它们,请使用替换...
Cause the trim function only trims characters from the ends of the string.
use Replace if you want to eliminate them everywhere...
来自 MSDN:
我想这是不言自明的。
From MSDN:
I guess that's self-explanatory.
Trim
仅删除字符串开头和结尾的字符。内部“-”字符不会被删除,就像内部空格一样。您需要Replace()
。Trim
only removes characters from the beginning and end of the string. Internal '-' characters will not be removed, any more than internal whitespace would. You wantReplace()
.其他人已经正确回答了 Trim 只修剪字符串开头和结尾的字符。使用:-
这假定原始字符串具有固定格式。至于性能,除非你要做一百万次这样的事情,否则我不会担心。
Others have answered correctly Trim only trims characters from the start and end of the string. Use:-
This assumes a fixed format in the original string. As to performance, unless you are doing a million of these I wouldn't worry about it.
修剪仅从开始和结束处删除。如果您想从字符串中删除,请使用替换。
Trim removes only from start and end. Use Replace if u want to remove from within the string.