adding zeros in objective-c string formats

余生长醉 提交于 2019-12-11 02:06:08

问题


Quick question: I am trying to fill in empty spaces with a specific number of zeroes in an NSString stringWithFormat formatting string.
For example, I want:

@"The number is %d", 5   // I want this to output 'the number is 05'
@"the number is %d", 10  // I want this to output 'the number is 10'

I know how to do this in Java, but I cant seem to find the same function in objective-c.

Any help would be great.


回答1:


If in Java you use System.out.printf(), then it's the same format syntax in Objective-C (and C, for that matter):

NSLog(@"The number is %02d", 5);
NSLog(@"The number is %02d", 10);



回答2:


In C you can use something like:

char res[255];
sprintf(res, "the number is %02d", 5);


来源:https://stackoverflow.com/questions/4697510/adding-zeros-in-objective-c-string-formats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!