Help in padding numerical strings
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
?
Be开发者_如何学运维st regards.
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.
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.
精彩评论