0

我需要从文件名 exp 中知道我有多少图像:我有图像调用:第一个文件:Splash_10001.jpg 最后一个文件:Splash_10098.jpg 我想插入然后数组..

 for(int i = 1; i <= IMAGE_COUNT; i++)
{
    UIImage* image = [UIImage imageNamed:[NSString stringWithFormat:@"%@%04d.%@",self.firstImageName,i,self.imageType]];
    NSLog(@"%d",i);
    [imgArray addObject:image];
}

我想用数字 98 替换 IMAGE_COUNT,但我需要从用户发送给我的字符串中获取数字:Splash_10098.jpg 我需要将 Splash_10098.jpg 分离为:nsstring:Splash_1 int:0098 nsstring:jpg 10x 全部!

4

4 回答 4

1

这取决于授予的字符串的输入是什么。在下文中,我将搜索点并返回到最大位数。顺便说一句,我只能建议使用多语言 NumberFormatter 而不是依赖默认转换。

  NSString * input = @"Splash_19001.jpg";
  NSRange r = [input rangeOfString:@"."];
  if(r.location>4){
    NSString * numberPart = [input substringWithRange: NSMakeRange(r.location-4,4)];
    NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
    [nf setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber * number = [nf numberFromString:numberPart];
    int val = [number intValue];
    NSLog(@"intValue=%d",val);
  }
于 2012-10-28T08:34:56.583 回答
0

如果数字长度在后缀中是固定的,那么使用子字符串而不是尝试删除前缀是有意义的。剥离扩展名并获取最后的 x 字符,将它们转换为 intintValueNSNumberFormatteriOS 建议的,尽管如果您确定字符串的格式,这可能是不必要的。

NSString *userProvidedString = @"Splash_10001.jpg";
NSString *numberString = [userProvidedString stringByDeletingPathExtension];
NSUInteger length = [numberString length];
NSInteger numberLength = 4;
if (length < numberLength)
{
     NSLog(@"Error in the string");
     return;
}
numberString = [numberString substringWithRange: NSMakeRange(length - 4, 4)];
NSInteger integer = [numberString integerValue];
// Do whatever you want with the integer.
于 2012-10-28T08:39:39.110 回答
0

使用Regex(NSRegularExpression在 iOS 中),这可以很容易地完成,

看一下这个,

NSError *error = NULL;
NSString *originalString = @"Splash_10098.jpg";
NSString *regexString = @"([^\?]*_[0-9])([0-9]*)(.)([a-z]*)";

NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:originalString options:NSRegularExpressionCaseInsensitive range:NSMakeRange(0, [originalString length])];

NSLog(@"FileName: %@", [originalString substringWithRange:[match rangeAtIndex:1]]);
NSLog(@"Total Count: %@", [originalString substringWithRange:[match rangeAtIndex:2]]);
NSLog(@"File type: %@", [originalString substringWithRange:[match rangeAtIndex:4]]);

结果:

FileName: Splash_1
Total Count: 0098
File type: jpg
于 2012-10-28T11:05:45.130 回答
0

我想这就是你要找的

NSString *stringUserSendsYou = @"Splash_10098.jpg";
int IMAGE_COUNT = [[[stringUserSendsYou stringByReplacingOccurrencesOfString:@"Splash_1" withString:@""] stringByReplacingOccurrencesOfString:@".jpg" withString:@""] integerValue];
于 2012-10-28T08:15:23.747 回答