Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate string by space using Objective-C?

Assume that I have a String like this:

hello world       this may     have lots   of sp:ace or little      space 

I would like to seperate this String to this:

@"hello", @"world", @"this", @"may", @"have", @"lots", @"of", @"sp:ace", @"or", @"little", @"space" 

Thank you.

like image 400
user448236 Avatar asked Jan 27 '11 09:01

user448236


People also ask

How to split a string in Objective-C?

Objective-C Language NSString Splitting If you need to split on a set of several different delimiters, use -[NSString componentsSeparatedByCharactersInSet:] . If you need to break a string into its individual characters, loop over the length of the string and convert each character into a new string.

How do you separate strings in space?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

How do you remove spaces from a string in Objective-C?

For those who are trying to remove space in the middle of a string, use [yourString stringByReplacingOccurrencesOfString:@" " withString:@""] .

How do I create an NSArray in Objective-C?

Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.


2 Answers

NSString *aString = @"hello world       this may     have lots   of sp:ace or little      space"; NSArray *array = [aString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; array = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != ''"]]; 
like image 57
vikingosegundo Avatar answered Sep 21 '22 02:09

vikingosegundo


I'd suggest a two-step aproach:

NSArray *wordsAndEmptyStrings = [yourLongString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSArray *words = [wordsAndEmptyStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]]; 
like image 44
danyowdee Avatar answered Sep 22 '22 02:09

danyowdee