Padding NSString not working

时光怂恿深爱的人放手 提交于 2019-12-12 14:28:54

问题


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

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?

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.

Example Goal Output:

Day       Hour      Name      Age

Does anybody know how to do this right?

I'm using ARC and iOS 5.

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

Thanks to all of you folks !!

Edit:

I have noticed that this works:

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

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


回答1:


Here is a way to do that :

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


来源:https://stackoverflow.com/questions/8642096/padding-nsstring-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!