Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

iphone - objective-c code to right pad a NSString?

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

For example want these strings:

Testing 123 Long String
Hello World
Short 

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

That is a 2nd column would like up.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...