将一个NSString中的字符替换为另一个NSString中的字符

时间:2013-10-09 17:05:55

标签: objective-c cocoa-touch nsstring

我有一个NSString,如@"12345",另一个像@"##-##-#"。逐个替换#中所有NSString字符的最佳方式是什么,所以它看起来像12-34-5

4 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分: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);

答案 2 :(得分: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);

答案 3 :(得分: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