0

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.

Akshay
  • 227
  • 2
  • 13

2 Answers2

2

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);
Sviatoslav Yakymiv
  • 7,887
  • 2
  • 23
  • 43
0

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.

MadhavanRP
  • 2,832
  • 1
  • 20
  • 26