Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic string format with NSString stringWithFormat

I've been trying to make a dynamic string format so that through user options precision or padding could be somewhat user defined.

An example includes, the padding of leading zeros as in the 24hour time format. In normal time format, the hours can be represented by a single digit, or a digit padded by a zero. This is represented in the string format:

...stringWithFormat:@"Hour: %02i", hour   // leading zero padded

and

...stringWithFormat:@"Hour: %i", hour     // not leading zero padded

What I would like to achieve is to have a variable containing either @"" or @"02" and have that variable presented in the format string between the % and the i.

I have done a couple of experiments and just can't seem to do this and am beginning to think that it's not possible with stringWithFormat.

I've tried:

...stringWithFormat:@"Hour: %%@i", padding, hour

...stringWithFormat:@"Hour: %@%i", padding, hour

and others.

Any ideas?

like image 884
Madivad Avatar asked Dec 04 '12 04:12

Madivad


2 Answers

There's a better way to do this.

... stringWithFormat:@"Hour: %0*i", length, hour]; // note the asterisk

where length is the number of digits you want. Use 1 to get no leading zeros, use 2 to get a length of 2 with leading zeros as needed.

FYI - to solve what you originally tried you need to do it in two steps:

NSString *dynFmt = [NSString stringWithFormat:@"Hour: %%%@i", padding];
NSString *res = [NSString stringWithFormat:dynFmt, hour];
like image 50
rmaddy Avatar answered Nov 05 '22 04:11

rmaddy


Use two steps:

    NSString* hourString=nil;
    if(...){
         hourString=[NSString stringWithFormat:@"%i", hour];
    }else{
         hourString=[NSString stringWithFormat:@"%02i", hour];
    }
    NSString* result=[NSString stringWithFormat:@"Hour: %@", hourString];

The following is considered a bad practice:

    NSString* formatString=nil;
    if(...){
         formatString=@"Hour: %i";
    }else{
         formatString=@"Hour: %02i";
    }
    NSString* result=[NSString stringWithFormat:formatString, hour];

because it's very dangerous to have a variable formatString, which can be used in many types of cracker attacks.

like image 34
Yuji Avatar answered Nov 05 '22 04:11

Yuji