dynamic string format with NSString stringWithFormat

后端 未结 3 1620
一向
一向 2021-02-04 14:37

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

相关标签:
3条回答
  • 2021-02-04 15:13

    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.

    0 讨论(0)
  • 2021-02-04 15:19

    I think you could build up your format in an entirely separate stage, then use that. Also, don't forget to escape one of the %'s to make it literal.

    NSString *format = [NSString stringWithFormat:@"%%%@i", padding];
    NSString *result = [NSString stringWithFormat:@"Hour: %@", format]; 
    

    update: oops maddy's answer pointed out a problem with mine: to escape a %, you should use %%, not \%. answer updated.

    0 讨论(0)
  • 2021-02-04 15:36

    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];
    
    0 讨论(0)
提交回复
热议问题