gpt4 book ai didi

iphone - 如何在 iOS 中提取字符串中两个分隔符之间的文本?

转载 作者:行者123 更新时间:2023-11-29 04:24:21 24 4
gpt4 key购买 nike

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

要提取的一些文本:

text text text text

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

some text to be extracted

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

text text text text

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

最佳答案

这是一种方法。

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

然后您采用 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");
}

关于iphone - 如何在 iOS 中提取字符串中两个分隔符之间的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12565643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com