views:

51

answers:

2

Hi,

trying to figure out how to add zeroes in front of a random generated number with dynamic length of the number. For example if the number is 10 characters long, I can print the number as stringWithFormat:@"%.10d",i

Since the numer can somtimes be shorter than maximum length, it needs zeroes to fill the maximum length of the number to fit the string.

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

The meaning of format string components:

  • 1st 0 - means that the number must be padded to specific width with zeros
  • 10 - required minimum width of output

For more information about format specifiers you can check this printf specification. I sometimes also use this shorter one - you can find your example there.

You can create your format string dynamically as well - you'll need to calculate maximum number length in advance (maxLength in example):

NSString* format = [NSString stringWithFormat:@"%%0%dd", maxLength];
NSString *s = [NSString stringWithFormat:format, 10];
NSLog(@"%@", s);
Vladimir
Thanks for the format specifier info.But the dynamic length still remains a question. Is it possible to get the required minimum width of the output to be dynamic depending on the maximum length of the number that should be padded?Example resultmax_length 1000 (4 digits) - result 0042max_length 100000 (6 digits) - result 003491
linge
Thanks, that solved it.
linge
A: 

I tested the suggestion of Vladimir but it does not work. I do not know why. This error message is given:

-[NSCFString stringWithFormat:]: unrecognized selector sent to instance 0x100002060

But this one is tested and worked fine:

for(int i = [number length]; i < maxLength; i++){
    ausgabe = [@"0" stringByAppendingString: ausgabe];
}
Marcel
How did you call that? It looks like you tried to call stringWithFormat method on NSString instance, but it is class method - you should call it only this way: [NSString stringWithFormat:...]. Instance methods are for example -initWithFormat: and -appendFormat: (in case of mutable string)
Vladimir