NSString *numberVector = @"( 1, 2, 3, 4)";
I want to get NSMutableArray from these numbers. How can I do this?
NSString *numberVector = @"( 1, 2, 3, 4)";
I want to get NSMutableArray from these numbers. How can I do this?
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.
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:@", "];
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);
See the code below, it should work:
NSCharacterSet *cSet = [NSCharacterSet characterSetWithCharactersInString:@" ()"];
numberVector = [numberVector stringByTrimmingCharactersInSet:cSet];
//specify delimiter below
NSArray *numbers = [numberVector componentsSeparatedByString:@", "];
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:@", "]