所以我有一个NSString,让我们说:NSString *mainString = @"My Name is Andrew (I like computers)";
我想从mainString中删除“(”到“)”中的所有内容。我想将“()”之间的所有内容放入subString。
例如:
NSString *mainString = @"My Name is Andrew (I like computers)";
NSString *subString;
//The code I need help with
mainString = @"y Name is Andrew ";
subString = @"I like computers";
我希望这是有道理的。这真的对我很有帮助。提前致谢。我一直在玩NSRange
和NSMutableStrings
,但我遇到了麻烦。提前谢谢。
答案 0 :(得分:9)
int startPosition = [mainString rangeOfString:@"("].location + 1;
int endPosition = [mainString rangeOfString:@")"].location;
NSRange range = NSMakeRange(startPosition, endPosition - startPosition);
NSString *subString = [mainString substringWithRange:range];
正如darvids0n在下面的评论中提到的那样:
mainString = [mainString substringToIndex:startPosition - 1]
答案 1 :(得分:7)
这可能是一种更简单的方法:
NSString *mainString = @"My Name is Andrew (I like computers)";
NSString *subString;
NSArray *array = [mainString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"()"]];
mainString = [array objectAtIndex:0]; // "My Name is Andrew "
subString = [array objectAtIndex:1]; // "I like computers"