How can I use the \t [tab] operator to format a NSString in columns?
Asked Answered
R

1

5

I would like to find a way to format a NSString like this:

Name:               John
Location:           Unknown
Type:               Unknown
Status:             Unknown

Right now I'm using this code to do it but the result is quite different:

The code:

serializedValue = [serializedValue stringByAppendingFormat:@"%@:\t\t%@\n",title, value];

Where title is the left column and value is the second one.

The result:

Name:       John
Location:       Unknown
Type:       Unknown
Status:     Unknown

Now, as you can see, adding always a constant number of tabs (\t), 2 in my case, doesn't do the trick, because some words in the left column are longer and some are shorter. I'm wondering if there is a simple way to do this that I'm not aware of.

Revamp answered 14/7, 2011 at 21:6 Comment(1)
do want to print the string in the console ?Gaselier
N
10
NSString *titleColumn = [[NSString stringWithFormat:@"%@:", title] stringByPaddingToLength:20 withString:@" " startingAtIndex:0];
serializedValue = [serializedValue stringByAppendingFormat:@"%@%@", titleColumn, value];

Btw, it would be more efficient to use an NSMutableString for serializedValue.

Nahshunn answered 14/7, 2011 at 21:17 Comment(3)
Just needs stringByAppendingFormat changed to stringByAppendingString :)Carlstrom
stringByAppendingFormat:@"%@%@", titleColumn, value]Rybinsk
What about for non-monospaced font?Cymose

© 2022 - 2024 — McMap. All rights reserved.