1

Is there a placeholder specifier in Objective-C? Something like %-15s which says 15 string characters starting from left? I want to print contents in a table format.

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

I am referring to How can I create table using ASCII in a console?, but the answer specified is for Java.

Matusalem Marques
  • 2,399
  • 2
  • 18
  • 28
John Doe
  • 2,225
  • 6
  • 16
  • 44

2 Answers2

1

According to the documentation on Objective-C string format specifiers, they comply with the IEEE printf specification, which allows you to specify field alignment and length.

This lets you use something like the following to get the results you want:

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

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

   // prints "|             foo | 1               |"

EDIT:

Per rmaddy's comments, if you're using [NSString stringWithFormat:] you may have to convert your NSStrings to C-strings to get this to work:

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

    NSLog(@"%@", result);
Matusalem Marques
  • 2,399
  • 2
  • 18
  • 28
  • The width specifiers do not work with `%@`. I opened a bug about this with Apple years ago. Still not supported. You need to use `%s` and `cStringUsingEncoding:` to convert the `NSString` to a C-string. – rmaddy May 01 '19 at 20:23
  • @rmaddy I tested the above code before posting and it works for me. Xcode 10.2.1, macOS 10.14.4. – Matusalem Marques May 01 '19 at 20:26
  • I tested it too. Just discovered something weird. Your code works fine using `NSLog`. But if you use `NSString *result = [NSString stringWithFormat:@"| %15@ | %-15@ |", rightAligned, leftAligned];` instead, it doesn't work. Very strange. – rmaddy May 01 '19 at 20:38
  • I just opened a question on this: https://stackoverflow.com/questions/55942555/a-format-specifier-such-as-15-works-in-nslog-but-not-with-nsstring-stringwit – rmaddy May 01 '19 at 20:51
1

Here's how you could translate this Java code to C (or Objective-C):

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

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

Note that in C, we use \n, not %n, for a newline. The puts function automatically appends a newline, so we don't need to use \n in the header strings.

C doesn't have an equivalent of Java's universal toString method (which allows "some data" + i to work in Java), so I have embedded the literal some data in the printf format string instead, and adjusted the adjacent format specifier accordingly.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848