Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 611
Greg Avatar asked Mar 22 '11 03:03

Greg


People also ask

What is NSString in Objective C?

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.

What does NSString mean?

A static, plain-text Unicode string object which you use when you need reference semantics or other Foundation-specific behavior.


1 Answers

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];
like image 178
Sherm Pendley Avatar answered Sep 22 '22 17:09

Sherm Pendley