我一直在努力消除NSString中的空白,但我try 过的方法都不管用.

我有"this is a test"个,我想得到"thisisatest"个.

我用了whitespaceCharacterSet,这应该可以消除空白.

NSString *search = [searchbar.text stringByTrimmingCharactersInSet:
                           [NSCharacterSet whitespaceCharacterSet]];

但我一直得到同样的空格字符串.有什么 idea 吗?

推荐答案

stringByTrimmingCharactersInSet只从字符串的开始和结束移除字符,而不是中间的字符.

1)如果只需要从字符串中删除给定字符(例如空格字符),请使用:

[yourString stringByReplacingOccurrencesOfString:@" " withString:@""]

2)如果你真的需要删除一组字符(不仅是空格字符,还有空格、制表符、不可拆分空格等任何空格字符),你可以使用whitespaceCharacterSet拆分字符串,然后将这些单词再次合并为一个字符串:

NSArray* words = [yourString componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString* nospacestring = [words componentsJoinedByString:@""];

Note that this last solution has the advantage of handling every whitespace character and not only spaces, but is a bit less efficient that the 100. So if you really only need to remove the space character and are sure you won't have any other whitespace character than the plain space char, use the first method.

Objective-c相关问答推荐

覆盖@property setter 和无限循环

Objective C 中的多个委托

如何在旋转时定义 CollectionView 的大小

处理 ARC 中的指针对指针所有权问题

如何构建一个 Objective-C 静态库?

didReceiveRemoteNotification:当应用程序处于后台并且未连接到Xcode时未调用fetchCompletionHandler

在 Objective-C/cocoa 中创建文件夹/目录

警告的含义在演示过程中!

具有多个嵌入 segues 的 ContainerView

从 NSRange 创建 UITextRange

Xcode:无法判断应用程序包

如何从 UIGestureRecognizer 获取 UITouch 位置

iOS是静态框架还是动态框架?

NSString 中子字符串的出现次数?

使 UILabel 的文本加粗

ARC 下的 NSString 属性应该是强的还是复制的?

iPhone如何在打字时获取UITextField的文本?

围绕其中心旋转 UIView 保持其大小

Objective C 消息分发机制

iOS 上的电话号码格式