使用嵌套for循环编写字符串模式

时间:2015-09-16 04:48:29

标签: objective-c command-line

我需要一个程序来打印字符串,如下面的目标c:

PARTHIBAN
 ARTHIBA
  RTHIB
   THI
    H

我尝试过(*)

代码:

int i,j,k,height;
NSString *name;
NSLog(@"Enter the name: %@",name);
NSLog(@"Enter the height:");
scanf("%i",&height);
for (i=height;i>=1;i--)
{
    for(k=height-1;k>=i;k--)
    {
        NSLog(@" ");
    }
    for (j=i; j>=1; j--)
    {
        NSLog(@"*");
    }
}

你能帮我打一下Objective-C中提到的字符串吗?

1 个答案:

答案 0 :(得分:2)

NSMutableString *name = [NSMutableString stringWithString:@"PARTHIBAN"];
while (name.length > 1) {
    [name deleteCharactersInRange:NSMakeRange(0, 1)];
    [name deleteCharactersInRange:NSMakeRange(name.length - 1, 1)];
    NSLog(@"name: %@", name);
}

编辑:我注意到您要打印带格式的字符串,试试这个:

NSMutableString *name = [NSMutableString stringWithString:@"PARTHIBAN"];
for (int i = 0; i < name.length / 2; i++ ) {
    [name replaceCharactersInRange:NSMakeRange(i, 1) withString:@" "];
    [name replaceCharactersInRange:NSMakeRange(name.length - 1 - i, 1) withString:@" "];
    NSLog(@"name: %@", name);
}