如何删除 NSString 右端的空格?
这会从字符串的两端删除空格:
NSString *newString = [oldString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
如何从字符串的右端删除空格?
更新:接受的答案中的代码 现在是 SSToolkit。耶!
This removes white space from both ends of a string:
NSString *newString = [oldString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
How do I remove white space from just the right end of a string?
UPDATE: The code from the accepted answer is now part of SSToolkit. Yay!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更新:快速基准测试显示Matt 自己的改编,基于 麦克斯' &我的,表现最好。
然后:
或用于前导空白:
它以抽象方式实现,因此您可以将其与任何可能的 NSCharacterSet 一起使用,whitespaceAndNewlineCharacterSet 只是其中之一。
为了方便起见,您可能需要添加这些包装方法:
编辑: 使用 charBuffer 恢复到初始版本以获得更好的性能。
UPDATE: A quick benchmark showed that Matt's own adaption, based on Max' & mine, performs best.
and then:
or for leading whitespace:
It's implemented in an abstract fashion so you can use it with any possible
NSCharacterSet
,whitespaceAndNewlineCharacterSet
being just one of them.For convenience you might want to add these wrapper methods:
Edit: reverted back to initial version using charBuffer for better performance.
以@Regexident & 的答案为基础@Max,我想出了以下方法:
这是 GHUnit 测试,当然都通过了:
我向 SSToolkit 添加了这些方法。
Building on the answers by @Regexident & @Max, I came up with the following methods:
And here are the GHUnit tests, which all pass of course:
I submitted a GitHub pull request to SSToolkit with these methods added.
需要稍作更改以解决最后一个非尾随字符为多字节的情况:
Needs a slight change to account for the case when last non-trailing character is multibyte: