In Objective-C, how to print out N spaces? (using stringWithCharacters)

Jeremy L picture Jeremy L · May 22, 2012 · Viewed 7.6k times · Source

The following is tried to print out N number of spaces (or 12 in the example):

NSLog(@"hello%@world", [NSString stringWithCharacters:" " length:12]);

const unichar arrayChars[] = {' '};
NSLog(@"hello%@world", [NSString stringWithCharacters:arrayChars length:12]);

const unichar oneChar = ' ';
NSLog(@"hello%@world", [NSString stringWithCharacters:&oneChar length:12]);

But they all print out weird things such as hello ÔÅÓñüÔÅ®Óñü®ÓüÅ®ÓñüÔ®ÓüÔÅ®world... I thought a "char array" is the same as a "string" and the same as a "pointer to a character"? The API spec says it is to be a "C array of Unicode characters" (by Unicode, is it UTF8? if it is, then it should be compatible with ASCII)... How to make it work and why those 3 ways won't work?

Answer

Joe picture Joe · May 22, 2012

You can use %*s to specify the width.

NSLog(@"Hello%*sWorld", 12, "");

Reference:

A field width, or precision, or both, may be indicated by an asterisk ( '*' ). In this case an argument of type int supplies the field width or precision. Applications shall ensure that arguments specifying field width, or precision, or both appear in that order before the argument, if any, to be converted.