本文介绍了从 NSString 中删除所有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试去除 NSString 中的空格,但我尝试过的方法都没有奏效.

I've been trying to get rid of the white spaces in an NSString, but none of the methods I've tried worked.

我有这是一个测试",我想得到thisisatest".

我使用了 whitespaceCharacterSet,它应该消除空格.

I've used whitespaceCharacterSet, which is supposed to eliminate the white spaces.

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

但我一直得到相同的带空格的字符串.有什么想法吗?

but I kept getting the same string with spaces. Any ideas?

推荐答案

stringByTrimmingCharactersInSet 只删除字符串开头和结尾的字符,不删除中间的字符.

stringByTrimmingCharactersInSet only removes characters from the beginning and the end of the string, not the ones in the middle.

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

1) If you need to remove only a given character (say the space character) from your string, use:

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

2) 如果您确实需要删除一组字符(即不仅是空格字符,还包括空格、制表符、牢不可破的空格等),您可以拆分字符串使用 whitespaceCharacterSet 然后在一个字符串中再次加入单词:

2) If you really need to remove a set of characters (namely not only the space character, but any whitespace character like space, tab, unbreakable space, etc), you could split your string using the whitespaceCharacterSet then joining the words again in one string:

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

请注意,最后一个解决方案的优点是可以处理每个空白字符,而不仅仅是空格,但比 stringByReplacingOccurrencesOfString:withString: 的效率要低一些.因此,如果您真的只需要删除空格字符并且确定除了普通空格字符之外没有任何其他空格字符,请使用第一种方法.

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 stringByReplacingOccurrencesOfString:withString:. 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.

这篇关于从 NSString 中删除所有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 11:27