4

So I have an NSString, lets say it: NSString *mainString = @"My Name is Andrew (I like computers)"; And I want remove everything from the "(" to the ")" from mainString. And I want to put everything in between the "()" into a subString.

For example:

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";

I hope this makes sense. It would really help me. Thanks in Advance. I've been playing with NSRange and NSMutableStrings but I'm having trouble. Thanks in advance.

Andrew
  • 3,874
  • 5
  • 39
  • 67

2 Answers2

9
int startPosition = [mainString rangeOfString:@"("].location + 1;
int endPosition   = [mainString rangeOfString:@")"].location;

NSRange range = NSMakeRange(startPosition, endPosition - startPosition);

NSString *subString = [mainString substringWithRange:range];

and as darvids0n has mentioned in below comment:

    mainString = [mainString substringToIndex:startPosition - 1]
Parth Bhatt
  • 19,381
  • 28
  • 133
  • 216
Robin
  • 10,011
  • 5
  • 49
  • 75
  • And then `string = [string substringToIndex:startPosition - 1]`. –  Aug 30 '11 at 04:45
  • no we created range in such a way that it will take care of the ")". so substringtoindex: is not required here – Robin Aug 30 '11 at 04:51
7

This is probably an easier way:

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"
antalkerekes
  • 2,128
  • 1
  • 20
  • 36
  • Thank you so much for this. I just realized I just used this code for probably the 10th time. It really helped me – Andrew Dec 01 '11 at 02:57