Search code examples
iosnsstringtrimnscharacterset

How to trim a string which is having substring in "( )"?


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.


Solution

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