试图找出如何在随机生成的数字前面添加零,并使用动态数字长度。 例如,如果数字长度为10个字符,我可以将数字打印为stringWithFormat:@“%。10d”,i
由于数字的长度可能短于最大长度,因此需要使用零来填充数字的最大长度以适应字符串。
- (void)method:(int)length{
int i = rand() % length;
NSLog (@"%@",[NSString stringWithFormat:@"%.'length'd",i]);
}
答案 0 :(得分:15)
NSLog (@"%@",[NSString stringWithFormat:@"%010d",i]);
格式字符串组件的含义:
有关格式说明符的详细信息,请查看此printf specification。我有时也使用这个shorter one - 你可以在那里找到你的例子。
您也可以动态创建格式字符串 - 您需要提前计算最大数字长度(例如maxLength):
NSString* format = [NSString stringWithFormat:@"%%0%dd", maxLength];
NSString *s = [NSString stringWithFormat:format, 10];
NSLog(@"%@", s);