How to split a string into substrings on iOS?

I got nsstring from server. Now I want to split it into the desired substring. How to break a line?

For example:

substring1: read from second character to 5th character

substring2: read 10 characters from the 6th character.

+80
string substring ios objective-c iphone
Feb 27 '09 at 9:17
source share
3 answers

You can also split the string with a substring using the NString componentsSeparatedByString method.

Example from the documentation:

NSString *list = @"Norman, Stanley, Fletcher"; NSArray *listItems = [list componentsSeparatedByString:@", "]; 
+206
Feb 27 '09 at 9:43
source share

There are several methods for this in NSString:

 [myString substringToIndex:index]; [myString substringFromIndex:index]; [myString substringWithRange:range]; 

See the documentation for NSString for more information.

+36
Feb 27 '09 at 9:20
source share

I wrote a small method for splitting strings in a certain number of parts. Please note that it only supports single delimiter characters. But I think this is an efficient way to split NSString.

 //split string into given number of parts -(NSArray*)splitString:(NSString*)string withDelimiter:(NSString*)delimiter inParts:(int)parts{ NSMutableArray* array = [NSMutableArray array]; NSUInteger len = [string length]; unichar buffer[len+1]; //put separator in buffer unichar separator[1]; [delimiter getCharacters:separator range:NSMakeRange(0, 1)]; [string getCharacters:buffer range:NSMakeRange(0, len)]; int startPosition = 0; int length = 0; for(int i = 0; i < len; i++) { //if array is parts-1 and the character was found add it to array if (buffer[i]==separator[0] && array.count < parts-1) { if (length>0) { [array addObject:[string substringWithRange:NSMakeRange(startPosition, length)]]; } startPosition += length+1; length = 0; if (array.count >= parts-1) { break; } }else{ length++; } } //add the last part of the string to the array [array addObject:[string substringFromIndex:startPosition]]; return array; } 
0
Dec 13 '16 at 10:24
source share



All Articles