本文介绍了objective-c代码右键填充NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给出一个代码示例,说明如何在objective-c中正确填充NSString吗?

Can someone give a code example of how to right pad an NSString in objective-c please?

例如想要这些字符串:

Testing 123 Long String
Hello World
Short

如果右边填充到12的列宽:然后在每个末尾添加一个刺XXX,它将给出:

if right padded to a column width of say 12: and then a sting "XXX" is added to the end of each, it would give:

Testing 123 xxx
Hello World xxx
Short       xxx

这是第二列想要的。

推荐答案

亚当走在正确的轨道上,但不完全在那里。你想要使用+ stringWithFormat:,但不像他建议的那样。如果要将someString填充到(比如说)至少12个字符,则可以使用宽度说明符作为格式的一部分。由于您希望结果左对齐,因此您需要在宽度说明符前加一个减号:

Adam is on the right track, but not quite there. You do want to use +stringWithFormat:, but not quite as he suggested. If you want to pad "someString" to (say) a minimum of 12 characters, you'd use a width specifier as part of the format. Since you want the result to be left-justified, you need to precede the width specifier with a minus:

NSString *padded = [NSString stringWithFormat:@"%-12@", someString];

或者,如果您希望结果完全 12个字符,那么可以使用最小和最大宽度说明符:

Or, if you wanted the result to be exactly 12 characters, you can use both minimum and maximum width specifiers:

NSString *padded = [NSString stringWithFormat:@"%-12.12@", someString];

这篇关于objective-c代码右键填充NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:21