如何在objective-c中解析String

时间:2012-07-06 10:03:36

标签: html objective-c ios xcode parsing

我想解析一个字符串来替换一些元素 如果我的字符串包含<ol>,那么我想解析<li>元素以用数字替换它们。

我知道我可以使用rangeOfString查看包含的字符串。

if ([myString rangeOfString:@"<ol>"].location != NSNotFound) {
    //Do stuff here  
}

我如何仅在<ol></ol>元素之间进行解析?

编辑1:这是我的解决方案

- (NSString *)parseOrderedList:(NSString *)str {


NSMutableString *html = [NSMutableString stringWithCapacity:[str length]];

NSScanner *scanner = [NSScanner scannerWithString:str];
NSString *tempText = nil;

while (![scanner isAtEnd])
{
    [scanner scanUpToString:@"<ol>" intoString:&tempText];
    [scanner scanUpToString:@"</ol>" intoString:&tempText];


    if (tempText != nil) {
        [html appendString:tempText];
        html = [[[html stringByReplacingOccurrencesOfString:@"</li>" withString:@" "] mutableCopy] autorelease];

            while ([html rangeOfString:@"<li>"].location != NSNotFound) {
                html = [[[html stringByReplacingOccurrencesOfString:@"<li>" withString:[NSString stringWithFormat:@"%i.", i]] mutableCopy] autorelease];
                i++;
            }

    }


    if (![scanner isAtEnd])
        [scanner setScanLocation:[scanner scanLocation] + 0];

    tempText = @" ";

}

return html;
}  

但是如何用当前的循环次数替换

  • ?我每次都是第一次计算。

  • 1 个答案:

    答案 0 :(得分:1)

    这样做

    NSString * aString = @"your string";
    NSMutableArray *substrings = [NSMutableArray alloc]init];
    NSScanner *scanner = [NSScanner scannerWithString:aString];
    [scanner scanUpToString:@"<ol>" intoString:nil]; // Scan all characters before <ol>
    while(![scanner isAtEnd]) 
    {
      NSString *substring = nil;
      [scanner scanString:@"<ol>" intoString:nil]; // Scan the <ol> character
      if([scanner scanUpToString:@"</ol>" intoString:&substring]) 
      {
      // If the space immediately followed the <ol>, this will be skipped
      [substrings addObject:substring];
      }
     [scanner scanUpToString:@"<ol>" intoString:nil]; // Scan all characters before next <ol>
    }
    

    U在nsmutablearray中有字符串,可用于替换字符串

    可以对其他标签重复相同的方法