NSString stringWithFormat问题 [英] NSString stringWithFormat question

查看:131
本文介绍了NSString stringWithFormat问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用NSString构建一个小表。

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

这是我有的

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

其中e是来自其他地方的NSString,v是一个float。

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

我得到的是

Grapes:20.3
Pomegranates:2.5
Oranges:15.1

如何修改我的格式来做这样的事情?

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

推荐答案

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]]);
}

输出:


Oranges:      15.10
Pomegranates:  2.50
Grapes:       20.30

这篇关于NSString stringWithFormat问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆