0

我想以某种方式缩短或占用更少的空间。

 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:"];
    }

任何帮助是极大的赞赏。

4

3 回答 3

2

您可以将 totalTime 设为可变字符串。然后,您可以将映射放入 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 参考

于 2013-06-19T13:23:33.950 回答
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:@""];
于 2013-06-19T17:12:54.493 回答
0

为 NSString 添加一个类别:

@implementation NSString (replace)

-(void) replace:(NSString*)old with:(NSString*)new{

self = [self stringByReplacingOccurrencesOfString:old  withString:new];
}

所以你只需要打电话: [totalTime replace:@"00:" with:@""];

于 2013-06-19T13:23:22.703 回答