Truncate part of NSString starting with a specific character

I have a line

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

Now I want to trim the string so that basically everything between the brackets, including the brackets, is truncated.

More precisely: I do not care what happens after the first bracket.

I can’t make it simple stringByReplacingOccurrencesOfString:because I can’t predict what will happen between the brackets. So, the resulting string should be:

"This is a string"
+3
source share
2 answers

One method:

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

Should also work for when '('

+7
source

should just be

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

if the bitket still exists only -1

0
source

Source: https://habr.com/ru/post/1709475/


All Articles