0

我在印度(IND)有一个字符串,现在我想修剪括号(IND)中包含的字符。我只想要“印度”

我正在尝试使用

  - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;

我不知道如何在字符集中提供括号请帮助我。

4

2 回答 2

2

此代码适用于任意数量的任何国家:

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);
于 2013-10-23T08:25:46.323 回答
0

您不能使用该函数,因为它会从字符串的末尾删除属于集合的一部分的字符。

例子:

//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:@""];

正则表达式假定括号内的国家/地区只有大写字母。

于 2013-10-23T09:01:42.257 回答