views:

372

answers:

3

I am trying to build a small table using NSString. I cannot seem to format the strings properly.

Here is what I have

[NSString stringWithFormat:@"%8@: %.6f",e,v]

where e is an NSString from somewhere else, and v is a float.

What I want is output something like this:

Grapes:       20.3
Pomegranates:  2.5
Oranges:      15.1

What I get is

Grapes:20.3
Pomegranates:2.5
Oranges:15.1

How can I fix my format to do something like this?

+1  A: 
NSDictionary* fruits = [NSDictionary dictionaryWithObjectsAndKeys:
                        [NSNumber numberWithFloat:20.3], @"Grapes",
                        [NSNumber numberWithFloat:2.5], @"Pomegranates",
                        [NSNumber numberWithFloat:15.1], @"Oranges",
                        nil];
NSUInteger longestNameLength = 0;
for (NSString* key in [fruits allKeys])
{
    NSUInteger keyLength = [key length];
    if (keyLength > longestNameLength)
    {
        longestNameLength = keyLength;
    }
}
for (NSString* key in [fruits allKeys])
{
    NSUInteger keyLength = [key length];
    NSNumber* object = [fruits objectForKey:key];
    NSUInteger padding = longestNameLength - keyLength + 1;
    NSLog(@"%@", [NSString stringWithFormat:@"%@:%*s%5.2f", key, padding, " ", [object floatValue]]);
}

Output:

Oranges:      15.10
Pomegranates:  2.50
Grapes:       20.30
Shaggy Frog
A: 

I think you want something like

[NSString stringWithFormat:@"%-9@ %6.1f",[e stringByAppendingString:@":"],v]

since you want padding in front of the float to make it fit the column, though if the NSString is longer than 8, it will break the columns.

%-8f left-aligns the string in a 9-character-wide column (9-wide since the : is appended to the string beforehand, which is done so the : is at the end of the string, not after padding spaces); %6.1f right-aligns the float in a 6-char field with 1 decimal place.

edit: also, if you're viewing the output as if it were HTML (through some sort of web view, for instance), that may be reducing any instances of more than one space to a single space.

Isaac
+1  A: 

you could try using - stringByPaddingToLength:withString:startingAtIndex:

Jonathan Lund