问题
I have a string
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 should be:
"This is a string"
回答1:
One method:
NSArray *components = [myOldString componentsSeparatedByString:@"("];
NSString *newString = [components objectAtIndex:0];
Should also work for the case where there isn't a '('
回答2:
should be simply
NSRange r = [myOldString rangeOfString:@"("]
NSString new string = [myOldString substringToIndex:r.location];
if the braket is still there just -1
来源:https://stackoverflow.com/questions/932273/truncate-part-of-an-nsstring-starting-at-a-particular-character