I want to extract only the names from the following string
bob!33@localhost @clement!17@localhost jack!03@localhost
and create an array [@"bob", @"clement", @"jack"]
.
I have tried NSString's componentsseparatedbystring:
but it didn't work as expected. So I am planning to go for regEx.
You can do it without regex as below (Assuming ! sign have uniform pattern in your all words),
NSString *names = @"bob!33@localhost @clement!17@localhost jack!03@localhost";
NSArray *namesarray = [names componentsSeparatedByString:@" "];
NSMutableArray *desiredArray = [[NSMutableArray alloc] initWithCapacity:0];
[namesarray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSRange rangeofsign = [(NSString*)obj rangeOfString:@"!"];
NSString *extractedName = [(NSString*)obj substringToIndex:rangeofsign.location];
[desiredArray addObject:extractedName];
}];
NSLog(@"%@",desiredArray);
output of above NSLog would be
(
bob,
"@clement",
jack
)
If you still want to get rid of @ symbol in above string you can always replace special characters in any string, for that check this
If you need further help, you can always leave comment
NSMutableArray* nameArray = [[NSMutableArray alloc] init];
NSArray* youarArray = [yourString componentsSeparatedByString:@" "];
for(NSString * nString in youarArray) {
NSArray* splitObj = [nString componentsSeparatedByString:@"!"];
[nameArray addObject:[splitObj[0]]];
}
NSLog(@"%@", nameArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With