You can do it by using NSCharacterSet
and componentsSeparatedByString
.
Solution :
// Your string
NSString *myString = @"Name: Tom Smith Old address street name : 31 Fox Road Dixton 0000";
// Seperating words which have more than 1 space with another word
NSArray *components = [myString componentsSeparatedByString:@" "];
NSString *newString = @"";
NSString *oldString = @"";
for (NSString *tempString in components)
{
// Creating new string
newString = [oldString stringByAppendingString:[tempString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
// Avoiding new line characters or extra spaces contained in the array
if (![oldString isEqualToString:newString])
{
newString = [newString stringByAppendingString:@"\n"];
oldString = newString;
}
}
NSLog(@"%@",newString);
or
You can use NSRegularExpression
NSString *pattern = [NSString stringWithFormat:@" {2,%d}",[myString length]];
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
NSString *output = [regex stringByReplacingMatchesInString:myString options:0 range:NSMakeRange(0, [myString length]) withTemplate:@"\n"];
NSLog(@"%@", output);