Truncate part of an NSString starting at a particular character

我是研究僧i 提交于 2019-12-19 09:55:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!