-2

我有一个NSString喜欢@"12345"和另一个喜欢@"##-##-#"。一个一个替换所有#字符的最佳方法是什么?NSString12-34-5

4

4 回答 4

2
NSString *original = @"12345";
NSString *toRepl = @"##-##-#";
for (int i = 0; i < original.length; i++) {
    unichar c = [original characterAtIndex:i];
    for (int j = 0; j < toRepl.length; j++) {
        if([toRepl characterAtIndex:j] == '#'){
            toRepl = [toRepl stringByReplacingCharactersInRange:NSMakeRange(j, 1) withString:[NSString stringWithFormat:@"%c", c]];
            break;
        }
    }
}
于 2013-10-09T17:32:54.333 回答
0

这是我对此的尝试,单循环并且不使用重载characterAtIndex

NSString *pattern = @"##-##-#";
NSString *replace = @"12345";
NSMutableString *result = [pattern mutableCopy];
NSRange searchRange = NSMakeRange(0, [pattern length]);
NSRange resultRange;

NSString *patternCheck = [pattern stringByReplacingOccurrencesOfString:@"-" withString:@""];

if ([replace length] == [patternCheck length]) {
    for (int i = 0; i < [replace length]; i++) {
        resultRange = [result rangeOfString:@"#" options:NSCaseInsensitiveSearch range:searchRange];
        [result replaceCharactersInRange:resultRange withString:[replace substringWithRange:NSMakeRange(i, 1)]];
    }
}
NSLog(@"pattern:%@ replace:%@ result:%@", pattern, replace, result);

将打印pattern:##-##-# replace:12345 result:12-34-5

于 2013-10-10T08:52:07.333 回答
0

单循环解决方案:

NSString *pattern = @"##-##-#";
NSString *fillWith = @"12345";

NSMutableString *result = [pattern mutableCopy];
__block NSUInteger index = 0; // Position into fillWith

// Loop over all characters in pattern:
[pattern enumerateSubstringsInRange:NSMakeRange(0, [pattern length])
                            options:NSStringEnumerationByComposedCharacterSequences
                         usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
     if ([substring isEqualToString:@"#"]) {
         if (index < [fillWith length]) {
             // Replace # by the next character from fillWith:
             [result replaceCharactersInRange:substringRange
                                   withString:[fillWith substringWithRange:NSMakeRange(index, 1)]];
             index++;
         } else {
             // Too many #'s in pattern:
             *stop = YES;
         }
     }
}];
NSLog(@"%@", result);
于 2013-10-09T17:55:16.940 回答
0

对不起,我看错了你的问题:

这是我测试过的有效解决方案。

NSString *string = @"123456";

NSString *string2 = @"##-##-##";

int i = 0;
do {
    NSRange rangeOfChar = [string2 rangeOfString:@"-"];

    NSLog(@"range %ld %ld",rangeOfChar.location,rangeOfChar.length);

    string = [NSString stringWithFormat:@"%@%@%@",[string substringToIndex:rangeOfChar.location+i],@"-",[string substringFromIndex:rangeOfChar.location+i]];


    string2 = [string2 stringByReplacingCharactersInRange:rangeOfChar withString:@""];

    i++;

} while ([string2 rangeOfString:@"-"].location!=NSNotFound);
于 2013-10-09T18:03:19.003 回答