动态创建NSString stringWithFormat:输出

时间:2010-08-21 20:13:30

标签: objective-c nsstring

试图找出如何在随机生成的数字前面添加零,并使用动态数字长度。 例如,如果数字长度为10个字符,我可以将数字打印为stringWithFormat:@“%。10d”,i

由于数字的长度可能短于最大长度,因此需要使用零来填充数字的最大长度以适应字符串。

- (void)method:(int)length{
int i = rand() % length;
NSLog (@"%@",[NSString stringWithFormat:@"%.'length'd",i]);
}

1 个答案:

答案 0 :(得分:15)

NSLog (@"%@",[NSString stringWithFormat:@"%010d",i]); 

格式字符串组件的含义:

  • 1st 0 - 表示必须用零填充数字到特定宽度
  • 10 - 所需的最小输出宽度

有关格式说明符的详细信息,请查看此printf specification。我有时也使用这个shorter one - 你可以在那里找到你的例子。

您也可以动态创建格式字符串 - 您需要提前计算最大数字长度(例如maxLength):

NSString* format = [NSString stringWithFormat:@"%%0%dd", maxLength];
NSString *s = [NSString stringWithFormat:format, 10];
NSLog(@"%@", s);