从另外两个NSMutableStrings创建NSMutableString

时间:2011-04-21 04:28:38

标签: objective-c nsmutablestring

我有两个字符串:

@"--U"@"-O-"并希望创建另一个NSMutableString,使@"-OU"使用两个分配。有谁知道我怎么能这样做?

3 个答案:

答案 0 :(得分:2)

注意,下面的代码假定s1和s2具有相同的长度,否则它会在某个时刻抛出异常,所以检查:)

- (NSMutableString *)concatString:(NSString *)s1 withString:(NSString *)s2
{
    NSMutableString *result = [NSMutableString stringWithCapacity:[s1 length]];
    for (int i = 0; i < [s1 length]; i++) {
        unichar c = [s1 characterAtIndex:i];
        if ( c != '-' ) {
            [result appendFormat:@"%c", c];
        }
        else {
            [result appendFormat:@"%c", [s2 characterAtIndex:i]];
        }
    }
    return result;
}

答案 1 :(得分:1)

    NSString *t1=@"-0-";
    NSString *t2=@"--U";

    NSString *temp1=[t1 substringWithRange:NSMakeRange(0, 2)];
    NSString *temp2=[t2 substringFromIndex:2];
    NSLog(@"%@",[NSString stringWithFormat:@"%@%@",temp1,temp2]);

答案 2 :(得分:1)

这个版本比Nick更啰嗦,但是把它分解为C函数和尾递归,所以它可能运行得更快。它还处理不同长度的字符串,选择镜像较短字符串的长度。

注意:我还没有运行此代码,因此它可能有错误或缺少明显的东西。

void recursiveStringMerge(unichar* string1, unichar* string2, unichar* result) {
    if (string1[0] == '\0' || string2[0] == '\0') {
        result[0] = '\0'; //properly end the string
        return; //no use in trying to add more to this string
    }
    else if (string1[0] != '-') {
        result[0] = string1[0];
    }
    else {
        result[0] = string2[0];
    }
    //move on to the next unichar in each array
    recursiveStringMerge(string1+1, string2+1, result+1);
}

- (NSMutableString *)concatString:(NSString *)s1 withString:(NSString *)s2 {
    NSUInteger resultLength;
    NSUInteger s1Length = [s1 length]+1; //ensure space for NULL with the +1
    NSUInteger s2Length = [s2 length]+1;

    resultLength = (s1Length <= s2Length) ? s1Length : s2Length; //only need the shortest

    unichar* result = malloc(resultLength*sizeof(unichar));
    unichar *string1 = calloc(s1Length, sizeof(unichar));
    [s1 getCharacters:buffer];
    unichar *string2 = calloc(s2Length, sizeof(unichar));
    [s2 getCharacters:buffer];

    recursiveStringMerge(string1, string2, result);
    return [NSString stringWithCharacters: result length: resultLength];
}