如何修剪“()”中具有子字符串的字符串?

时间:2013-10-23 07:52:46

标签: ios nsstring trim nscharacterset

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

我正在尝试使用

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

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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:@""];

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