I've a string in India(IND), now i want to trim the characters which are included in parentheses(IND). I just want "India"

I'm trying to use

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

i don't know how to provide parentheses in character set Please help me.

有帮助吗?

解决方案

This code will work for any number of any countries:

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);

其他提示

You cannot use that function because it removes characters which are part of the set from the ends of the string.

Example:

//Produces "ndia"
[@"India(IND)" stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"(IND)"]];

I suggest you use regex to trim.

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\([A-Z]*\\)" options:NULL error:nil];
NSString *trimmedString = [regex stringByReplacingMatchesInString:sample options:0 range:NSMakeRange(0, [sample length]) withTemplate:@""];

The regex assumes you only have capital letters for countries inside parentheses.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top