2011-04-21 59 views
0

创建的NSMutableString我有两个字符串:从另外两个NSMutableStrings

@"--U"@"-O-"并希望创建另一个的NSMutableString,使用两个已知条件,使@"-OU"。有谁知道我该怎么做?

回答

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

这是完美的谢谢。诀窍是使用unichar :) – locoboy 2011-04-21 05:13:03

+1

还有一个关于代码的假设:如果s1和s2在同一位置都有非“ - ”字符,则来自s1的字符将优先:) – Nick 2011-04-21 05:57:37

1
NSString *[email protected]"-0-"; 
    NSString *[email protected]"--U"; 

    NSString *temp1=[t1 substringWithRange:NSMakeRange(0, 2)]; 
    NSString *temp2=[t2 substringFromIndex:2]; 
    NSLog(@"%@",[NSString stringWithFormat:@"%@%@",temp1,temp2]); 
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]; 
} 
相关问题