views:

1080

answers:

2

This should be a simple one, but my brains are a bit hazy today:

I have an NSString * myOldString = @"This is a string (and this part is between brackets)"

Now, I want to truncate the string in such a way, that basically everything between the brackets, including the brackets, is truncated.

More precisely: I don't care what is happening after the first bracket at all.

I can't do a simple stringByReplacingOccurrencesOfString, because I cannot predict what will be between the brackets. So, the resulting string would be:

"This is a string"

Thank you for your input

A: 

should be simply

NSRange r = [myOldString rangeOfString:@"("]
NSString new string = [myOldString substringToIndex:r.location];

if the braket is still there just -1

Bluephlame
I'd just add a check that r.location != NSNotFound -- just in case...
Alex Martelli
Thanks, that works, but (see Tom below) I had to build in some extra code to make sure that it didn't go out of bounds if there was no bracket.
+2  A: 

One method:

NSArray *components = [myOldString componentsSeparatedByString:@"("];
NSString *newString = [components objectAtIndex:0];

Should also work for the case where there isn't a '('

Tom