删除部分NSString并将其复制到另一个NSString中

时间:2011-08-30 04:38:26

标签: iphone objective-c nsstring substring nsrange

所以我有一个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";

我希望这是有道理的。这真的对我很有帮助。提前致谢。我一直在玩NSRangeNSMutableStrings,但我遇到了麻烦。提前谢谢。

2 个答案:

答案 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"