Help in padding numerical strings

橙三吉。 提交于 2019-12-10 14:53:25

问题


I am trying to generate a numerical string by padding the number with zeroes to the left.

0 would become 00000 1 would become 00001 10 would become 00010

I want to create five character NSString by padding the number with zeroes.

I read this Create NSString by repeating another string a given number of times but the output is an NSMutableString.

How can I implement this algorithm with the output as an NSString?

Best regards.


回答1:


You can accomplish this by calling

[NSString stringWithFormat:@"%05d", [theNumber intValue]];

where theNumber is the NSString containing the number you want to format.

For further reading, you may want to look at Apple's string formatting guide or the Wikipedia entry for printf.




回答2:


One quick & simple way to do it:

unsigned int num = 10;  // example value
NSString *immutable = [NSString stringWithFormat:@"%.5u", num];

If you actually really want to use the long-winded approach from the example you read, you can send a “copy” message to a mutable string to get an immutable copy. This holds for all mutable types.



来源:https://stackoverflow.com/questions/5358702/help-in-padding-numerical-strings

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