0

我有以下字符串,如何提取位于两个分隔符之间的文本:

some text to be extracted

text text text text

= = = = = = = = = = = = =

some text to be extracted

= = = = = = = = = = = = =

text text text text

我还希望将两个定界符与文本一起返回。如何用 Objective-C 做到这一点?

4

2 回答 2

1

这是一种方法。

您必须找到分隔符字符串所在的所有范围。

然后你取 2 x 2 的范围来提取它们之间的字符串:

    NSString *str = @"text text text text --- some text to be extracted... --- text text text text";

    NSString *myDelimiterString = @"---";

    NSMutableArray *arrayOfRangeForOccurrences = [[NSMutableArray alloc] init];
    NSUInteger length = [str length];
    NSRange range = NSMakeRange(0, length);
    while(range.location != NSNotFound)
    {
        range = [str rangeOfString:myDelimiterString options:0 range:range];
        if(range.location != NSNotFound)
        {    
            [arrayOfRangeForOccurrences addObject:[NSValue valueWithRange:range]];
            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
        }
    }

    //at least 2 delimiters have been found, we can extract a string
    if (arrayOfRangeForOccurrences.count >= 2) {
        //Extracting first text :
        NSRange firstRangeForDelimiter = [[arrayOfRangeForOccurrences objectAtIndex:0] rangeValue];
        NSRange secondRangeForDelimiter = [[arrayOfRangeForOccurrences objectAtIndex:1]rangeValue];

        NSRange rSub = NSMakeRange(firstRangeForDelimiter.location + firstRangeForDelimiter.length, secondRangeForDelimiter.location - firstRangeForDelimiter.location - firstRangeForDelimiter.length);
        NSString *myExtractedText = [str substringWithRange:rSub];
        NSLog(@"myExtractedText is : %@", myExtractedText);
    } else {
        NSLog(@"No pair of delimiter found");
    }
于 2015-04-16T10:14:20.533 回答
0

你可以使用类似下面的代码行,

NSArray *arrChars = [@"Your,String,for,test" componentsSeparatedByString:@","];

因此,您将获得由 , 分隔的部分字符串。

希望这可以帮助您实现您想要的。

于 2012-09-24T13:08:51.700 回答