且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在ObjC中获取两个其他字符串之间的字符串

更新时间:2023-02-22 11:59:43

Jacques提供的正则表达式解决方案,以及要求iOS 4.0及更高版本的警告是正确的。使用正则表达式也很慢,如果搜索表达式是已知的字符串常量,那就太过分了。

The regular expressions solution that Jacques gives works, and the caveat of requiring iOS 4.0 and later is true. Using regular expressions is also quite slow, and an overkill if the search expressions are known string constants.

您可以使用 NSString 上的方法或名为 NSScanner ,自从iPhone OS 2.0开始以及很久以前就已经可用,因为在Mac OS X 10.0实际上之前:)。

You can solve the problem using methods on NSString, or a class named NSScanner, both have been available since iPhone OS 2.0 and long before that, since before Mac OS X 10.0 actually :).

所以你想要的是一个关于 NSString 的新方法是这样的?

So what you want is a new method on NSString like this?

@interface NSString (CWAddition)
- (NSString*) stringBetweenString:(NSString*)start andString:(NSString*)end;
@end

没问题,我们假设我们应该返回 nil 是不能找到这样的字符串。

No problem, and we assume we should return nil is no such strings could be found.

仅使用 NSString 的实现是非常直接:

The implementation using NSString only is quite straight forward:

@implementation NSString (NSAddition)
- (NSString*) stringBetweenString:(NSString*)start andString:(NSString*)end {
    NSRange startRange = [self rangeOfString:start];
    if (startRange.location != NSNotFound) {
        NSRange targetRange;
        targetRange.location = startRange.location + startRange.length;
        targetRange.length = [self length] - targetRange.location;   
        NSRange endRange = [self rangeOfString:end options:0 range:targetRange];
        if (endRange.location != NSNotFound) {
           targetRange.length = endRange.location - targetRange.location;
           return [self substringWithRange:targetRange];
        }
    }
    return nil;
}
@end

或者您可以使用 NSScanner class:

Or you could do the implementation using the NSScanner class:

@implementation NSString (NSAddition)
- (NSString*) stringBetweenString:(NSString*)start andString:(NSString*)end {
    NSScanner* scanner = [NSScanner scannerWithString:self];
    [scanner setCharactersToBeSkipped:nil];
    [scanner scanUpToString:start intoString:NULL];
    if ([scanner scanString:start intoString:NULL]) {
        NSString* result = nil;
        if ([scanner scanUpToString:end intoString:&result]) {
            return result;
        }
    }
    return nil;
}
@end