组合2个字符串以获得目标c中两个字符串中每个字符的交替序列的输出

时间:2017-10-26 06:05:21

标签: objective-c

我们如何组合2个字符串中的字符并显示输出? string1string2合并为string3提供如下输出。我找不到任何解决方案,这段代码对我有用。

string1=@"ACEG";
string2=@"BDF";
Output:
ABCDEFG
// Anybody has an alternative solution to get this result.
{
    NSString *name1=@"ACEG";
    NSString *name2=@"BDF";
    NSString *name1Andname2=@"";
    NSInteger number;   
    NSMutableArray *charArray1 = [[NSMutableArray alloc] initWithCapacity:name1.length];
    NSMutableArray *charArray2 = [[NSMutableArray alloc] initWithCapacity:name2.length];
    for (int i=0; i < name1.length;i++) {
        NSString *ichar1  = [NSString stringWithFormat:@"%c", [name1 characterAtIndex:i]];
        [charArray1 addObject:ichar1];
    }
    for (int i=0; i < name2.length;i++) {
        NSString *ichar2  = [NSString stringWithFormat:@"%c", [name2 characterAtIndex:i]];
        [charArray2 addObject:ichar2];  
    }
    if (name1.length>name2.length)
    {
        number=name1.length;
    }
    else
    {
        number=name2.length;
    }
    for (int i=0; i <= number;i++) {
        if(name1.length>i)
        {
            name1Andname2=[name1Andname2 stringByAppendingString:charArray1[i]];
        }
        if(name2.length>i)
        {
        name1Andname2=[name1Andname2 stringByAppendingString:charArray2[i]];
        }
    }
    NSLog(@"%@",name1Andname2);
}

1 个答案:

答案 0 :(得分:1)

由于您希望结果是两个字符串中每个字符的交替,因此您当前的方法基本上是实现它的方法。虽然您的代码可能无法使用所有可能的Unicode字符,因为并非所有字符都可以用长度为1的字符串表示。下面是一个更强大的解决方案,适用于任何字符。

NSString *name1=@"ACEG";
NSString *name2=@"BDF";

NSMutableArray *firstChars = [NSMutableArray array];

[name1 enumerateSubstringsInRange:NSMakeRange(0, name1.length) options: NSStringEnumerationByComposedCharacterSequences
    usingBlock: ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    [firstChars addObject: substring];
}];

NSMutableArray *secondChars = [NSMutableArray array];

[name2 enumerateSubstringsInRange:NSMakeRange(0, name2.length) options: NSStringEnumerationByComposedCharacterSequences
    usingBlock: ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    [secondChars addObject: substring];
}];

NSMutableString *result = [[NSMutableString alloc] init];
NSInteger maxLen = MAX(firstChars.count, secondChars.count);
for (NSInteger i = 0; i < maxLen; i++) {
    if (i < firstChars.count) {
        [result appendString:firstChars[i]];
    }
    if (i < secondChars.count) {
        [result appendString:secondChars[i]];
    }
}

NSLog(@"Final string: %@", result);