Reputation: 837
NSString *numberVector = @"( 1, 2, 3, 4)";
I want to get NSMutableArray from these numbers. How can I do this?
Upvotes: 1
Views: 297
Reputation: 1437
With this:
NSString *numberVector = @"( 1, 2, 3, 4)";
EDIT
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"&([^;])*;" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [numberVector stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
NSArray *listItems = [[modifiedString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsSeparatedByString:@", "]
Upvotes: -2
Reputation: 8460
try like this it'l works fine for any type of data it accepts only numbers.
NSString *numberVector = @"(\n 1,\n 2,\n 3,\n 4\n)";
NSString *onlyNumbers = [numberVector stringByReplacingOccurrencesOfString:@"[^0-9,]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [numberVector length])];
NSArray *numbers=[onlyNumbers componentsSeparatedByString:@","];
NSLog(@"%@",numbers);
Upvotes: 1
Reputation: 39988
This is the simpler one, convert it to json string first then convert is to array using NSJSONSerialization
NSString *numberVector = @"( 1, 2, 3, 4)";
numberVector = [numberVector stringByReplacingOccurrencesOfString:@"(" withString:@"["];
numberVector = [numberVector stringByReplacingOccurrencesOfString:@")" withString:@"]"];
NSError* error;
NSMutableArray *arr = [NSJSONSerialization JSONObjectWithData:[numberVector dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
Update
This will work for both @"( 1, 2, 3, 4)"
and @"(\n 1,\n 2,\n 3,\n 4\n)"
as json string can have new line and spaces.
P.S This will work for iOS 5.0 or greater for other iOS you can use SBJSON or other parsing library available.
Upvotes: 3
Reputation: 12243
See the code below, it should work:
NSCharacterSet *cSet = [NSCharacterSet characterSetWithCharactersInString:@" ()"];
numberVector = [numberVector stringByTrimmingCharactersInSet:cSet];
//specify delimiter below
NSArray *numbers = [numberVector componentsSeparatedByString:@", "];
Upvotes: 0
Reputation: 40211
If you know that this is exactly your format and don't have to be flexible in the amount of spaces, brackets or commas:
NSCharacterSet *trimSet = [NSCharacterSet characterSetWithCharactersInString:@" ()"];
numberVector = [numberVector stringByTrimmingCharactersInSet:trimSet];
NSArray *numbers = [numberVector componentsSeparatedByString:@", "];
Upvotes: 1