18

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)

Guy Daher
  • 5,526
  • 5
  • 42
  • 67

3 Answers3

28

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

zaph
  • 111,848
  • 21
  • 189
  • 228
23

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

Amit Shah
  • 4,176
  • 2
  • 22
  • 26
2

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;
       }
}
felixwcf
  • 2,078
  • 1
  • 28
  • 45
iAkshay
  • 1,143
  • 1
  • 13
  • 35