NSString stringWithFormat的动态字符串格式 [英] 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.
一个例子包括,以24小时时间格式填充前导零。在正常时间格式中,小时数可以用一个数字表示,也可以用零填充的数字表示。这以字符串格式表示:
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
和
...stringWithFormat:@"Hour: %i", hour // not leading zero padded
我想要实现的是变量包含 @
或 @02
并在%
和 i
之间的格式字符串中显示该变量。
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
.
我做了几个实验,似乎无法做到这一点,我开始认为用 stringWithFormat
。
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
.
我试过了:
... stringWithFormat:@小时: %% @ i,填充,小时
... stringWithFormat:@小时:%@%i ,填充,小时
和其他人。
任何想法?
推荐答案
有一种更好的方法可以做到这一点。
There's a better way to do this.
... stringWithFormat:@"Hour: %0*i", length, hour]; // note the asterisk
其中长度
是你想要的位数。使用 1
获取无前导零,使用 2
根据需要获得前导零的长度为2。
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];
这篇关于NSString stringWithFormat的动态字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!