jerry
jerry

Reputation: 274

Unable to extracting a substring from an NSString

I have an input string in the format

"Jerry Lane"(angle bracket)[email protected](bracket closed),"Harry Potter"(angle bracket)[email protected](bracket closed),"Indiana Jones",(angle bracket)[email protected](bracket closed),"Tom Cruise"(angle bracket)[email protected](bracket closed)

Here, i am supposed to first separate the string on the basis of comma delimiter, which would give me a separate string like

"Jerry Lane"(angle bracket)[email protected](bracket closed)

Then i need to save extract the string between the <> brackets, which is essentially the string "[email protected]". I am using the following code, but it is giving me the following error:

Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFConstantString substringWithRange:]: Range or index out of bounds'

-(NSArray *)parseString:(NSString *)string
{
  if(string)
  {
    NSArray *myArray = [string componentsSeparatedByString:@","];
    for(NSMutableString *myString in myArray)
    {
        NSRange start,end;
        start = [myString rangeOfString:@"<"];
        end = [myString rangeOfString:@">"];
        if(start.location != NSNotFound && end.location != NSNotFound)
        {
            NSString *emailAddress = [myString substringWithRange:NSMakeRange(start.location,end.location)];
            NSString *name = [myString substringToIndex:start.location];

            NSDictionary *myDictionary = [[NSDictionary alloc] init];
            [myDictionary setValue:emailAddress forKey:@"Dhruvil Vyas"];
            [testArray addObject:myDictionary];

        }
    }
}

return testArray;

}

Upvotes: 0

Views: 347

Answers (2)

Midhun MP
Midhun MP

Reputation: 107121

borrrden's answer is correct. Here is another way to do this.

-(NSArray *)parseString:(NSString *)string
{
  if(string)
  {
    NSArray *myArray = [string componentsSeparatedByString:@","];
    for(NSMutableString *myString in myArray)
    {
        NSArray *tempNameArray = [myString componentsSeparatedByString:@"<"];
        NSString *email = [tempNameArray objectAtIndex:1];

        NSArray *tempMailArray = [email componentsSeparatedByString:@">"];

        NSString *emailAddress = [tempMailArray objectAtIndex:0];
        NSString *name = [tempNameArray objectAtIndex:0];

        NSDictionary *myDictionary = [[NSDictionary alloc] init];
        [myDictionary setValue:emailAddress forKey:@"Dhruvil Vyas"];
        [testArray addObject:myDictionary];
    }
  }

 return testArray;
}

Upvotes: 1

borrrden
borrrden

Reputation: 33421

The arguments that substring takes are the start position and the length

Not the start position and the end position.

More Info

Upvotes: 4

Related Questions