0

假设我有以下字符串:

Mary had a little lamb, she also had a little sheep.

我的目标是在句号前后提取每个单词had。(在这种情况下a little sheep)。

我试过这样:

- (NSInteger)indexOf:(NSString*)substring from:(NSInteger)starts {
    NSRange r;
    r.location = starts;
    r.length = [self length] - r.location;

    NSRange index = [self rangeOfString:substring options:NSLiteralSearch range:r];
    if (index.location == NSNotFound) {
        return -1;
    }
    return index.location + index.length;
}

如:

NSInteger sheepSpot = [string indexOf:@"had" from:23];

// I know that I want to grab everything after the index of sheepSpot but before the period.
// Suppose now that I have an arbitrary number of periods in the sentence, how can I extract the above text without getting the wrong thing?
4

2 回答 2

1

此代码将找到最后一个“had”和最后一个句点,并为您提供介于两者之间的所有内容:

NSString *text = @"Mary had a little lamb, she also had a little sheep.";
NSString *subtext = nil;
NSRange lastHadRange = [text rangeOfString:@"had" options:NSBackwardsSearch];
if (lastHadRange.location != NSNotFound) {
    NSRange lastPeriodRange = [text rangeOfString:@"." options:NSBackwardsSearch];
    if (lastPeriodRange.location != NSNotFound) {
        NSUInteger start = lastHadRange.location + lastHadRange.length;
        NSUInteger length = lastPeriodRange.location - start;
        subtext = [text substringWithRange:NSMakeRange(start, length)];
    }
}

NSLog(@"Subtext is: %@", subtext);
于 2013-03-22T04:24:24.097 回答
1

试试这个:

-(NSRange)lastRangeOf:(NSString *)substring inString:(NSString *)string{
   return  [string rangeOfString:substring options:NSBackwardsSearch];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
    NSString *string=@"had Mary had a little lamb, she also had a had little sheep.";
    NSString *word=@"had";
    NSRange hadRange=[self lastRangeOf:word inString:string];
    NSInteger start=hadRange.location+word.length;
    NSInteger lengthToCut=string.length-start;
    NSString *substring=[string substringWithRange:NSMakeRange(start,lengthToCut)];
    NSLog(@"->%@",substring);
}
于 2013-03-22T03:49:38.883 回答