我有以下字符串,如何提取位于两个分隔符之间的文本:
some text to be extracted
:
text text text text
= = = = = = = = = = = = =
some text to be extracted
= = = = = = = = = = = = =
text text text text
我还要将两个分隔符与文本一起返回。 如何用Objective-C完成?
答案 0 :(得分:1)
这是一种方法。
您必须找到分隔符字符串所在的所有范围。
然后你将范围2乘以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");
}
答案 1 :(得分:0)
你可以使用类似下面的代码,
NSArray *arrChars = [@"Your,String,for,test" componentsSeparatedByString:@","];
所以你将把部分字符串分隔为。
希望这可以帮助你实现你想要的目标。