修剪 NSString 末尾的空格
我需要删除字符串末尾的空格。我怎样才能做到这一点? 示例:如果字符串是 "Hello "
它必须变成 "Hello"
I need to remove spaces from the end of a string. How can I do that?
Example: if string is "Hello "
it must become "Hello"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
摘自此处的答案:https://stackoverflow.com/a/5691567/251012
Taken from this answer here: https://stackoverflow.com/a/5691567/251012
另一个解决方案涉及创建可变字符串:
Another solution involves creating mutable string:
给你...
所以现在就打电话吧。假设您有一个前面有空格、末尾有空格的字符串,而您只想删除末尾的空格,则可以这样调用它:
resultString
将在后面没有空格结尾。Here you go...
So now just call it. Supposing you have a string that has spaces on the front and spaces on the end and you just want to remove the spaces on the end, you can call it like this:
resultString
will then have no spaces at the end.还有许多其他字符集。根据你的要求自己检查一下。
There are many other CharacterSets. Check it yourself as per your requirement.
要仅从 Swift 中的字符串的开头和结尾删除空格:
Swift 3
以前的 Swift 版本
To remove whitespace from only the beginning and end of a string in Swift:
Swift 3
Previous Swift Versions
Swift 版本
仅修剪字符串末尾的空格:
修剪字符串两侧的空格:
Swift version
Only trims spaces at the end of the String:
Trims spaces on both sides of the String:
这将仅删除您选择的尾随字符。
This will remove only the trailing characters of your choice.
在 Swift 中
修剪空间和字符串两侧的换行符:
In Swift
To trim space & newline from both side of the String:
Objective-C 中仅修剪一端而不是两端的简单解决方案:
以及仅修剪开头的对称实用程序:
A simple solution to only trim one end instead of both ends in Objective-C:
And a symmetrical utility for trimming the beginning only:
要修剪所有尾随空白字符(我猜这实际上是您的意图),以下是一个非常干净的&简洁的方法来做到这一点。
Swift 5:
Objective-C:
一行,带有一些正则表达式。
To trim all trailing whitespace characters (I'm guessing that is actually your intent), the following is a pretty clean & concise way to do it.
Swift 5:
Objective-C:
One line, with a dash of regex.
解决方案如下所述: 如何从右端删除空格NSString?
将以下类别添加到 NSString:
并按如下方式使用它:
The solution is described here: How to remove whitespace from right end of NSString?
Add the following categories to NSString:
And you use it as such:
我想出了这个函数,它的行为基本上与 Alex 的答案中的一个类似:
whitespaceCharacterSet
除了空格本身还包括制表符,在我的情况下无法出现。所以我想简单的比较就足够了。I came up with this function, which basically behaves similarly to one in the answer by Alex:
whitespaceCharacterSet
besides space itself includes also tab character, which in my case could not appear. So i guess a plain comparison could suffice.let string = " Test Trimmed String "
要删除空格和换行符,请使用下面的代码:-
let str_trimmed = yourString.trimmingCharacters(in: .whitespacesAndNewlines)
要仅删除字符串中的空格,请使用下面的 代码代码:-
let str_trimmed = yourString.trimmingCharacters(in: .whitespaces)
let string = " Test Trimmed String "
For Removing white Space and New line use below code :-
let str_trimmed = yourString.trimmingCharacters(in: .whitespacesAndNewlines)
For Removing only Spaces from string use below code :-
let str_trimmed = yourString.trimmingCharacters(in: .whitespaces)