我试着得到这样的输出:
A BA ABA BABA ABA BA A
但我得到了这个:
AB ABA ABAB ABABA ABABAB
这就是我尝试过的,而且我完全没想到了。
NSString *strA = @"A";
NSString *strB = @"B";
// Capacity does not limit the length, it's just an initial capacity
NSMutableString *result = [NSMutableString stringWithCapacity:[strA length] * 10];
for (int i = 0; i <= 4; i++)
{
[result appendString:strA];
[result appendString:strB];
NSLog(@"%@", result);
}
答案 0 :(得分:0)
以下是代码:
NSString *strA = @"A";
NSString *strB = @"B";
int maxLength = 4;
NSMutableString *result = [NSMutableString string];
NSString *stringToAdd = nil;
for (int i = 0; i < maxLength * 2; i++) {
if (i < maxLength) {
stringToAdd = [stringToAdd isEqualToString:strA] ? strB : strA;
[result insertString:stringToAdd atIndex:0];
} else {
[result deleteCharactersInRange:NSMakeRange(0, 1)];
}
NSLog(@"%@", result);
}
结果:
A
BA
ABA
BABA
ABA
BA
A