NSLog默认中断行

时间:2014-02-23 02:58:30

标签: ios objective-c

我是Objective-C的新手,我开始学习简单的东西。在这种情况下,我想使用pyramid符号创建*

问题:每次打印*时,都会包含换行符。如何摆脱它来创造金字塔外观?我以为我必须添加\n才能在我添加的Break line文字中引起换行符。

现在,我有这个代码来创建金字塔:

    //Pyramid
    int a,b;
    int x=5;

    for(a = 1; a <= x; a++){

        for(b=1; b<=a; b++){
            NSLog(@"*");
        }

        NSLog(@"Break line");

    }

结果:

2014-02-23 10:44:35.264 Pyramid[614:303] *
2014-02-23 10:44:35.266 Pyramid[614:303] Break line
2014-02-23 10:44:35.267 Pyramid[614:303] *
2014-02-23 10:44:35.267 Pyramid[614:303] *
2014-02-23 10:44:35.267 Pyramid[614:303] Break line
2014-02-23 10:44:35.268 Pyramid[614:303] *
2014-02-23 10:44:35.268 Pyramid[614:303] *
2014-02-23 10:44:35.269 Pyramid[614:303] *
2014-02-23 10:44:35.269 Pyramid[614:303] Break line
2014-02-23 10:44:35.269 Pyramid[614:303] *
2014-02-23 10:44:35.270 Pyramid[614:303] *
2014-02-23 10:44:35.270 Pyramid[614:303] *
2014-02-23 10:44:35.270 Pyramid[614:303] *
2014-02-23 10:44:35.271 Pyramid[614:303] Break line
2014-02-23 10:44:35.271 Pyramid[614:303] *
2014-02-23 10:44:35.272 Pyramid[614:303] *
2014-02-23 10:44:35.272 Pyramid[614:303] *
2014-02-23 10:44:35.272 Pyramid[614:303] *
2014-02-23 10:44:35.273 Pyramid[614:303] *
2014-02-23 10:44:35.273 Pyramid[614:303] Break line

2 个答案:

答案 0 :(得分:5)

NSLog总是在最后输出换行符,以及开头的其他信息。

您可以使用printf("*");输出到控制台而无需换行。如果需要换行符,请添加\n

for (NSUInteger outerIndex = 1; outerIndex <= 5; ++outerIndex) {
    for (NSUInteger innerIndex = 1; innerIndex <= outerIndex; ++innerIndex) {
        printf("*");
    }

    printf("\n");
}

答案 1 :(得分:1)

如评论中所述,NSLog将始终只输出一行,您将无法像Java那样避免这样做。或者,您应该查看构建字符串(如此处所述:Shortcuts in Objective-C to concatenate NSStrings)。

一个例子:

//Pyramid
int a,b;
int x=5;

for(a = 1; a <= x; a++){
    NSMutableString *string = [NSMutableString string];
    for(b=1; b <= a; b++){
        [string appendString:@"*"];
    }

    NSLog(@"%@", string);
}