12

I have a string NSString *Original=@"88) 12-sep-2012"; or Original=@"8) blablabla";

I want to print only the characters before the ")" so how to find the index of the character ")". or how could i do it?

Thanks in advance.

zrzka
  • 20,249
  • 5
  • 47
  • 73
fadd
  • 584
  • 4
  • 16
  • 41

6 Answers6

18

To print the characters before the first right paren, you can do this:

NSString *str = [[yourString componentsSeparatedByString:@")"] objectAtIndex:0];
NSLog(@"%@", str);

// If you need the character index:
NSUInteger index = str.length;
aleclarson
  • 18,087
  • 14
  • 64
  • 91
Padavan
  • 1,056
  • 1
  • 11
  • 32
10

U can find index of the character ")" like this:

NSString *Original=@"88) 12-sep-2012";
NSRange range = [Original rangeOfString:@")"];
if(range.location != NSNotFound)
{
 NSString *result = [Original substringWithRange:NSMakeRange(0, range.location)];
}
Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132
6

You can use the following code to see the characters before ")"

   // this would split the string into values which would be stored in an array
   NSArray *splitStringArray = [yourString componentsSeparatedByString:@")"];
   // this would display the characters before the character ")"
   NSLog(@"%@", [splitStringArray objectAtIndex:0]);
Vimal Venugopalan
  • 4,091
  • 3
  • 16
  • 25
3
NSUInteger index = [Original rangeOfString:@")"];

NSString *result = [Original substringWithRange:NSMakeRange(0, index)];
freestyler
  • 5,224
  • 2
  • 32
  • 39
3

try the below code to get the index of a particular character in a string:-

NSString *string = @"88) 12-sep-2012";
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@")"];
NSRange range = [string rangeOfCharacterFromSet:charSet];

if (range.location == NSNotFound) 
{
    // ... oops
}
else {
    NSLog(@"---%d", range.location);
    // range.location is the index of character )
}

and to get the string before the ) character use this:-

NSString *str = [[string componentsSeparatedByString:@")"] objectAtIndex:0];
Ravi Sharma
  • 975
  • 11
  • 29
1

Another soluation:

NSString *Original=@"88) 12-sep-2012";
NSRange range = [Original rangeOfString:@")"];
NSString *result = Original;

if (range.location != NSNotFound)
{
    result = [Original substringToIndex:range.location];
}

NSLog(@"Result: %@", result);
Gloomcore
  • 940
  • 7
  • 11