填充 NSString 不起作用 [英] Padding NSString not working

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

问题描述

我已经读到要左填充 NSString 你需要做的就是:

I have read that to left-pad an NSString all you need to do is this:

NSString *paddedStr = [NSString stringWithFormat:@"%-20.20@ %-20.20@", 
                          aString, anotherSting];

但是,那行不通!!我不知道为什么.我尝试了很多组合都没有成功.示例:

But, that does not work !! I don´t know why. I have tried a lot of combinations without success. Examples:

NSString *paddedStr = [NSString stringWithFormat:@"%-20s@", " ", myString];

但那种方式既丑陋又……丑陋.它只是在字符串 (myString) 之前附加 20 倍的字符 (" "),这不是我们需要的,对吗?

but that way is ugly and ... ugly. It just append 20 times the char (" ") before the string (myString) and that is not what we need right?

目标是将 NSString 格式化为显示两列或更多列,每列 20 个字符,而不管行中字符串的长度如何.

The goal is to have an NSString formatted to present two or more columns of 20 chars each one no matter the length of the string within a row.

示例目标输出:

Day       Hour      Name      Age

有人知道怎么做吗?

我使用的是 ARC 和 iOS 5.

I'm using ARC and iOS 5.

实际上,格式化的字符串将使用 NSFileHandle 写入文件.

And actually, the formatted string is going to be written to file using NSFileHandle.

谢谢大家!!

我注意到这有效:

NSString *str = [NSString stringWithFormat:@"%-10.10s %-10.10s", 
                    [strOne UTF8String], [strTwo UTF8String]];

但是……我们也不想要 C 风格的字符串.

But... We don't want C-style strings either.

推荐答案

这里有一个方法:

NSString *paddedStr = [NSString stringWithFormat:@"%@%@", 
                       [@"day" stringByPaddingToLength:20
                                            withString:@" "
                                       startingAtIndex:0], 
                       [@"Hour" stringByPaddingToLength:20
                                             withString:@" "
                                        startingAtIndex:0]];

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

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