gpt4 book ai didi

ios - 从 NSString 获取最大值是 NSArray

转载 作者:行者123 更新时间:2023-11-28 22:31:23 24 4
gpt4 key购买 nike

我有一个 NSArray,例如它有以下表示文件的字符串。

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

假设文件是​​ {prefix}{number}.xml

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

最佳答案

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;

}
}

关于ios - 从 NSString 获取最大值是 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17354385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com