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)
Asked
Active
Viewed 1.4k times
18

Guy Daher
- 5,526
- 5
- 42
- 67
3 Answers
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;
}
}