我想让它变得更短或占用更少的空间。
totalTime = [self timeFormatted:([currentFeed duration].intValue)-1];
NSString *word = @":00:";
if ([totalTime rangeOfString:word].location == NSNotFound) {
totalTime = [totalTime stringByReplacingOccurrencesOfString:@"00:" withString:@""];
totalTime = [totalTime stringByReplacingOccurrencesOfString:@"01:" withString:@"1:"];
totalTime = [totalTime stringByReplacingOccurrencesOfString:@"02:" withString:@"2:"];
totalTime = [totalTime stringByReplacingOccurrencesOfString:@"03:" withString:@"3:"];
totalTime = [totalTime stringByReplacingOccurrencesOfString:@"04:" withString:@"4:"];
totalTime = [totalTime stringByReplacingOccurrencesOfString:@"05:" withString:@"5:"];
totalTime = [totalTime stringByReplacingOccurrencesOfString:@"06:" withString:@"6:"];
totalTime = [totalTime stringByReplacingOccurrencesOfString:@"07:" withString:@"7:"];
totalTime = [totalTime stringByReplacingOccurrencesOfString:@"08:" withString:@"8:"];
totalTime = [totalTime stringByReplacingOccurrencesOfString:@"09:" withString:@"9:"];
}
非常感谢任何帮助。
答案 0 :(得分:2)
您可以将totalTime设为mutableString。然后,您可以将映射放入NSDictionary并迭代它。
NSMutableString *ms = [[totalTime mutableCopy] autorelease];
NSDictionary *d = @{@"00":@"", @"01:":@"1:", @"02:":@"2:" /* ... */};
[d enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[ms replaceOccurrencesOfString:key withString:obj options:NSCaseInsensitiveSearch range:NSMakeRange(0, [ms length])];
}];
totalTime = ms;
顺便说一句,如果您要设置日期格式,请查看NSDateFormatter reference。
答案 1 :(得分:1)
采用与正则表达式不同的方法:
NSError *error = NULL;
// replace 0X: with X: where X is 1-9
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"0([1-9]:)" options:0 error:&error];
date = [regex stringByReplacingMatchesInString:date options:0 range:NSMakeRange(0,date.length) withTemplate:@"$1"];
// remove 00: if not preceded by :
regex = [NSRegularExpression regularExpressionWithPattern:@"(?<!:)00:" options:0 error:&error];
date = [regex stringByReplacingMatchesInString:date options:0 range:NSMakeRange(0,date.length) withTemplate:@""];
答案 2 :(得分:0)
为NSString添加一个类别:
@implementation NSString (replace)
-(void) replace:(NSString*)old with:(NSString*)new{
self = [self stringByReplacingOccurrencesOfString:old withString:new];
}
所以你只需要打电话:
[totalTime replace:@"00:" with:@""];