【问题标题】:How to get the first different range of two string如何获得两个字符串的第一个不同范围
【发布时间】:2015-11-12 10:30:35
【问题描述】:

我有两个字符串,如下所示:

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

现在我想为两个字符串获取第一个不同的字符串:路径 1 的“桌面”和路径 2 的“文档/测试”。如果有超过 2 个 NSString 怎么办 有什么算法可以实现吗?

【问题讨论】:

    标签: objective-c nsstring


    【解决方案1】:

    试试这样的

    -(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:@"/"]]);
    

    【讨论】:

      猜你喜欢
      • 2014-05-06
      • 1970-01-01
      • 2019-07-16
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 2014-03-07
      相关资源
      最近更新 更多