开发者

creating NSMutableString from two other NSMutableStrings

I have two strings:

@"--U开发者_开发知识库" and @"-O-" and would like to create another NSMutableString that makes @"-OU" using the two givens. Does anyone know how I can do this?


Note, the following code assumes that s1 and s2 have the same length, otherwise it will throw an exception at some point, so do the checking :)

- (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;
}


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

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


This version is a bit more long-winded than Nick's, but breaks the thing down into C functions and tail recursion, so it may run faster. It also handles strings of different lengths, choosing to mirror the shorter string's length.

NOTE: I have not run this code yet, so it may be buggy or be missing something obvious.

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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜