0

您将如何从下面的长字符串中提取“19”?这就是我的做法,但我想知道,有没有比这更好/更快的方法?

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);
4

2 回答 2

4

componentsSeparatedByString当您只需要一小段原始字符串时,使用效率非常低。您不必要地解析整个字符串。

解决方案实际上取决于字符串的格式。如果您想要始终位于第一对括号中的子字符串,那么使用rangeOfString获取 first(和 first会更有效)。然后你提取两者之间的部分。

示例(没有任何适当的错误检查):

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];
于 2013-06-06T04:00:31.210 回答
0

试试这个

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 
于 2013-06-06T03:59:48.357 回答