如何获得第一个不同范围的两个字符串

时间:2015-11-12 10:30:36

标签: objective-c nsstring

我有两个字符串如下:

NSString *path1 = @"/Users/user/Desktop/AAA/BBB/1.txt";
NSString *path2 = @"/Users/user/Document/test/AAA/CCC/2.txt";

现在我想获得两个字符串的第一个不同的字符串:path1的“Desktop”和path2的“Document / test”。如果有超过2个NSString怎么样? 有没有算法来实现这个?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情

-(NSString *)findDiferentIn:(NSArray *)first By:(NSArray *)second{

    for (int i = 0; i < [first count]; i++) {
        if (![second objectAtIndex:i]) {
            return [first objectAtIndex:i];
        }else{
            if (![[first objectAtIndex:i] isEqualToString:[second objectAtIndex:i]]) {
                return [first objectAtIndex:i];
            }
        }
    }

    return @"";
}

使用:

NSString *path1 = @"/Users/user/Desktop/AAA/BBB/1.txt";
NSString *path2 = @"/Users/user/Document/test/AAA/CCC/2.txt";

NSLog(@"diferent in first string: %@", [self findDiferentIn:[path1 componentsSeparatedByString:@"/"] By:[path2 componentsSeparatedByString:@"/"]]);
NSLog(@"diferent in second string: %@", [self findDiferentIn:[path2 componentsSeparatedByString:@"/"] By:[path1 componentsSeparatedByString:@"/"]]);