0

我有一个NSArray例如具有以下代表文件的字符串。

"abc1.xml"
"abc2.xml"
"cde1.xml"
"cde2.xml"
"cde3.xml"
"def6.xml"
"def7.xml"

想象一下文件是{prefix}{number}.xml

有没有一种简单的方法可以找到{number}以前缀开头的文件的最大文件"abc"

4

1 回答 1

2
NSString *prefix = @"abc"; // adjust the prefix as needed
NSUInteger max = 0;

for (NSString *filename in myArray) {

    // if the prefix matches...
    if (filename.length >= prefix.length && [[filename substringToIndex:prefix.length] isEqualToString:prefix]) {

        // take away every character that's not a number
        NSString *numberAsString = [[filename componentsSeparatedByCharactersInSet:
                [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] 
                componentsJoinedByString:@""];

        // turn the NSString into an int
        NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
        [f setNumberStyle:NSNumberFormatterDecimalStyle];
        int n = [[f numberFromString:numberAsString] integerValue];

        // update the maximum value if necessary
        if (n > max) max = n;

    }
}
于 2013-06-27T23:05:56.917 回答