objective-c code to right pad a NSString?

前端 未结 6 1358
死守一世寂寞
死守一世寂寞 2020-12-06 01:26

Can someone give a code example of how to right pad an NSString in objective-c please?

For example want these strings:

Testing 123 Long String
Hello          


        
6条回答
  •  北海茫月
    2020-12-06 02:04

    Adam is on the right track, but not quite there. You do want to use +stringWithFormat:, but not quite as he suggested. If you want to pad "someString" to (say) a minimum of 12 characters, you'd use a width specifier as part of the format. Since you want the result to be left-justified, you need to precede the width specifier with a minus:

    NSString *padded = [NSString stringWithFormat:@"%-12@", someString];
    

    Or, if you wanted the result to be exactly 12 characters, you can use both minimum and maximum width specifiers:

    NSString *padded = [NSString stringWithFormat:@"%-12.12@", someString];
    

提交回复
热议问题