从NSString获取子字符串,直到到达特定单词

时间:2012-02-11 19:09:49

标签: ios objective-c xcode

我们说我有NSString@"Country Address Tel:number"。 如何获取Tel之前的子字符串? (国家地址) 然后我该如何获取Tel之后的子字符串? (数)

3 个答案:

答案 0 :(得分:28)

使用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输出:

  

preTel:国家地址
  postTel:数字

答案 1 :(得分:23)

最简单的方法是,如果你知道分隔符,(如果它总是:)你可以使用它:

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

将你的字符串分成两部分,并为每个子字符串

提供数组

答案 2 :(得分:2)

这是我已成功实施的zaph答案的扩展。

-(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;
       }
}