我在印度(IND)的字符串,现在我要修剪其包括在括号(IND)的字符。我只是想“印度”如何修剪在“()”中有子字符串的字符串?
我试图使用
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;
我不知道如何提供括号中的字符集 请帮助我。
我在印度(IND)的字符串,现在我要修剪其包括在括号(IND)的字符。我只是想“印度”如何修剪在“()”中有子字符串的字符串?
我试图使用
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;
我不知道如何提供括号中的字符集 请帮助我。
这段代码为任何数量的任何国家开展工作:
NSString *string = @"India(IND) United States(US)";
NSInteger openParenthesLocation;
NSInteger closeParenthesLocation;
do {
openParenthesLocation = [string rangeOfString:@"("].location;
closeParenthesLocation = [string rangeOfString:@")"].location;
if((openParenthesLocation == NSNotFound) || (closeParenthesLocation == NSNotFound)) break;
string = [string stringByReplacingCharactersInRange:NSMakeRange(openParenthesLocation, closeParenthesLocation - openParenthesLocation + 1) withString:@""];
} while (openParenthesLocation < closeParenthesLocation);
,因为它除去了一组从字符串的两端部分字符无法使用该功能。
例子:
//Produces "ndia"
[@"India(IND)" stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"(IND)"]];
我建议你使用正则表达式来修剪。
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\([A-Z]*\\)" options:NULL error:nil];
NSString *trimmedString = [regex stringByReplacingMatchesInString:sample options:0 range:NSMakeRange(0, [sample length]) withTemplate:@""];
正则表达式假设你只有在括号内国家的大写字母。
我的本意不是删除大写字母。只是为了删除palenthesis内的内容。 – Akshay
@Akshay您可以修改正则表达式来括号内的任何内容相匹配,不只是首都 – MadhavanRP
是啊谢谢你,我得到了它 – Akshay
完美....... –
它的工作:-) – Akshay