yhl
yhl

Reputation: 689

String Manipulation: More advanced substring

How would you extract "19" from the long string below? Here's how I'd do it but was wondering, is there a better/faster way than this?

NSString *myString = @"13.5 Points-(19) 38 Points-(50) 50 Points-(215) 4.3 Points-105.8 Points-21";
NSArray  *myArray  = [myString componentsSeparatedByString:@"-"];

NSString *splitString  = [myArray        objectAtIndex:1             ];
NSRange  range         = [splitString    rangeOfString:@")"          ];
NSString *newString    = [splitString substringToIndex:range.location];

NSString *newString2 = [newString stringByReplacingOccurrencesOfString:@"(" withString:@""];

NSLog(@"newString2: %@", newString2);

Upvotes: 0

Views: 100

Answers (2)

rmaddy
rmaddy

Reputation: 318794

Using componentsSeparatedByString is very inefficient when all you want is one little piece of the original string. You needlessly parse the entire string.

The solution really depends on what format the string will have. If you want the substring that will always be in the first pair of parentheses then it would be more efficient to use rangeOfString to get the first ( and the first ). Then you extract the piece between the two.

Example (without any proper error checking):

NSString *myString = @"13.5 Points-(19) 38 Points-(50) 50 Points-(215) 4.3 Points-105.8 Points-21";
NSRange openRange = [myString rangeOfString:@"("];
NSRange closeRange = [myString rangeOfString:@")"];

NSRange resultRange = NSMakeRange(openRange.location + 1, closeRange.location - openRange.location - 1);
NSString *result = [myString substringWithRange:resultRange];

Upvotes: 4

Deepesh Gairola
Deepesh Gairola

Reputation: 1242

Try this

NSString *myString = @"13.5 Points-(19) 38 Points-(50) 50 Points-(215) 4.3 Points-105.8 Points-21";
NSArray *strArr = [myString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString: @"()"]];

NSLog(@"myString..%@",[strArr objectAtIndex:1]);// myString..19 

Upvotes: 0

Related Questions