Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - Split string into array

How would I do this? I'm new to Objective-C but I can't find anything that would help me do this.

NSArray *splitLine = [currentLine componentsSeparatedByString:@":%@",notNumber];

Where notNumber is a string that represents anything that isn't a number. So I want to separate a string where there are colons separated by strings that aren't numbers. (I want to avoid splitting at times i.e. 3:00pm, but split at iCal parameters like DESCRIPTION: and LOCATION:.)

like image 569
user2623825 Avatar asked Aug 30 '26 02:08

user2623825


2 Answers

You can do this in several steps, like this. I have not compiled this code, but it should at least give you an idea of what to do.

1) Create a regex object to match your separators:

NSString *regexString = @"DESCRIPTION:\s|LOCATION:\s"; // or whatever makes sense for your scenario
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:regexString
                                          options:NSRegularExpressionCaseInsensitive
                                            error:nil];

2) Replace all the different separators matching your regex with just one separator:

NSRange range = NSMakeRange(0, string.length);
NSString *string2 = [regex stringByReplacingMatchesInString:string
                                                     options:0
                                                       range:range
                                                withTemplate:@"SEPARATOR"];

3) Split the string!

NSArray *elements = [string2 componentsSeparatedByString:@"SEPARATOR"];
like image 192
TotoroTotoro Avatar answered Aug 31 '26 17:08

TotoroTotoro


Shortest solution for splitting string.

NSString *str = @"Please split me to form array of words"; 
NSArray *wordsArray  = [str componentsSeparatedByString:@" "];
like image 24
handiansom Avatar answered Aug 31 '26 16:08

handiansom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!