如果你只想用一个字符填充,你可以使用stringWithFormat - 基本上是printf。下面我给出一些我构建的例子来说明,所以它不会用完框,但你只需要注释掉你不想让它工作的那些。
// To get 50 spaces
NSString * s50 = [NSString stringWithFormat:@"%*s", 50, ""];
// Pad with these characters, select only 1
// This will pad with spaces
char * pad = "";
// This will pad with minuses - you need enough to fill the whole field
char * pad = "-------------------------------------------------------";
// Some string
NSString * s = @"Hi there";
// Here back and front are just int's. They must be, but they can be calculated,
// e.g. you could have this to pad to 50
int back = 50 - s.length; if ( back < 0 ) back = 0;
// Pad s at the back
int back = 20;
NSString * sBack = [NSString stringWithFormat:@"%@%*s", s, back, pad];
// Pad s in front
int front = 10;
NSString * sFront = [NSString stringWithFormat:@"%*s%@", front, pad, s];
// Pad s both sides
NSString * sBoth = [NSString stringWithFormat:@"%*s%@%*s", front, pad, s, back, pad];
请注意,此处的数量是参数化的。我使用例如50 在第一行,但也可以是 n,只要 n 是一个 int 并且您可以使用它来执行计算,将其存储在 n 和填充中。代码中有一个例子。
这是一个输出示例
2020-11-04 08:16:22.908828+0200 FormatSpecifiers[768:15293] [Hi there-------------------------------------------------------]
2020-11-04 08:16:22.908931+0200 FormatSpecifiers[768:15293] [-------------------------------------------------------Hi there]
2020-11-04 08:16:22.908992+0200 FormatSpecifiers[768:15293] [-------------------------------------------------------Hi there-------------------------------------------------------]
我只是展示如何填充组合字符串。要组合字符串当然只需使用stringByAppendingString 例如
NSString * s = [a stringByAppendingString:b];
然后您可以根据s.length 进行计算,例如如示例所示。