Guy Daher
Guy Daher

Reputation: 5601

Get a substring from an NSString until arriving to a specific word

Let us say I have this NSString: @"Country Address Tel:number". How can I do to get the substring that is before Tel? (Country Address ) And then How can I do to get the substring that is after Tel? (number)

Upvotes: 18

Views: 14419

Answers (3)

iAkshay
iAkshay

Reputation: 1263

Here is an extension of zaph's answer that I've implemented successfully.

-(NSString*)stringBeforeString:(NSString*)match inString:(NSString*)string
{
      if ([string rangeOfString:match].location != NSNotFound)
      {
            NSString *preMatch;

            NSScanner *scanner = [NSScanner scannerWithString:string];
                   [scanner scanUpToString:match intoString:&preMatch];

            return preMatch;
      }
      else
      {
            return string;
      }
}

-(NSString*)stringAfterString:(NSString*)match inString:(NSString*)string
 {   
       if ([string rangeOfString:match].location != NSNotFound)
       {
            NSScanner *scanner = [NSScanner scannerWithString:string];

            [scanner scanUpToString:match intoString:nil];

             NSString *postMatch;

             if(string.length == scanner.scanLocation)
             {
                   postMatch = [string substringFromIndex:scanner.scanLocation];
             }
             else
             {
                   postMatch = [string substringFromIndex:scanner.scanLocation + match.length];
             }

             return postMatch;
       }
       else
       {
             return string;
       }
}

Upvotes: 2

zaph
zaph

Reputation: 112857

Use NSScanner:

NSString *string = @"Country Address Tel:number";
NSString *match = @"tel:";
NSString *preTel;
NSString *postTel;

NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner scanUpToString:match intoString:&preTel];

[scanner scanString:match intoString:nil];
postTel = [string substringFromIndex:scanner.scanLocation];

NSLog(@"preTel: %@", preTel);
NSLog(@"postTel: %@", postTel);

NSLog output:

preTel: Country Address
postTel: number

Upvotes: 28

Amit Shah
Amit Shah

Reputation: 4164

Easiest way is if you know the delimiter, (if it is always :) you can use this:

NSArray *substrings = [myString componentsSeparatedByString:@":"];
NSString *first = [substrings objectAtIndex:0];
NSString *second = [substrings objectAtIndex:1];

that will split your string into two pieces, and give you the array with each substring

Upvotes: 23

Related Questions