Objective-C 字符串中是否有占位符说明符?

Is there a placeholder specifier in Objective-C string?

Objective-C中是否有占位符说明符?像 %-15s 这样的东西表示从左边开始有 15 个字符串字符?我想以 table 格式打印内容。

+-----+------+
| foo | 1    |
+-----+------+

我指的是 How can I create table using ASCII in a console?,但指定的答案是 Java。

根据 Objective-C string format specifiers, they comply with the IEEE printf specification 上的文档,它允许您指定字段对齐方式和长度。

这让您可以使用类似下面的方法来获得您想要的结果:

    NSString *rightAligned = @"foo";
    NSString *leftAligned = @"1";

    NSLog(@"| %15@ | %-15@ |", rightAligned, leftAligned);

   // prints "|             foo | 1               |"

编辑:

根据 rmaddy 的评论,如果您正在使用 [NSString stringWithFormat:],您可能必须将 NSString 转换为 C 字符串才能使其正常工作:

    NSString *result = [NSString stringWithFormat:@"| %15s | %-15s |",
        [rightAligned cStringUsingEncoding:NSUTF8StringEncoding],
        [leftAligned cStringUsingEncoding:NSUTF8StringEncoding]];

    NSLog(@"%@", result);

以下是将 this Java code 翻译成 C(或 Objective-C)的方法:

puts("+-----------------+------+");
puts("| Column name     | ID   |");
puts("+-----------------+------+");

for (int i = 0; i < 5; i++) {
    printf("| some data%-8d | %-4d |\n", i, i * i);
}

请注意,在 C 中,我们使用 \n 而不是 %n 作为换行符。 puts 函数会自动添加一个换行符,因此我们不需要在 header 字符串中使用 \n

C 没有等效于 Java 的通用 toString 方法(它允许 "some data" + i 在 Java 中工作),所以我嵌入了改为 printf 格式字符串中的文字 some data,并相应地调整相邻的格式说明符。