0

我有两个字符串:

@"--U"并且@"-O-"想创建另一个@"-OU"使用这两个给定的 NSMutableString 。有谁知道我该怎么做?

4

3 回答 3

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;
}
于 2011-04-21T04:39:07.263 回答
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];
}
于 2011-04-21T05:23:28.350 回答
1
    NSString *t1=@"-0-";
    NSString *t2=@"--U";

    NSString *temp1=[t1 substringWithRange:NSMakeRange(0, 2)];
    NSString *temp2=[t2 substringFromIndex:2];
    NSLog(@"%@",[NSString stringWithFormat:@"%@%@",temp1,temp2]);
于 2011-04-21T04:56:49.617 回答