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?
You can use
%*s
to specify the width.Reference:
This is probably the fastest method:
The reason your current code isn't working is because
+stringWithCharacters:
expects an array with a length of characters of 12, while your array is only 1 character in length{' '}
. So, to fix, you must create a buffer for your array (in this case, we use achar
array, not aunichar
, because we can easilymemset
a char array, but not aunichar
array).The method I provided above is probably the fastest that is possible with a dynamic length. If you are willing to use GCC extensions, and you have a fixed size array of spaces you need, you can do this:
Unfortunately, that extension doesn't work with variables, so it must be a constant.
Through the magic of GCC extensions and preprocessor macros, I give you.... THE REPEATENATOR! Simply pass in a string (or a char), and it will do the rest! Buy now, costs you only $19.95, operators are standing by! (Based on the idea suggested by @JeremyL)
This will get you what you want:
I think the issue you have is you are misinterpreting what
+(NSString *)stringWithCharacters:length:
is supposed to do. It's not supposed to repeat the characters, but instead copy them from the array into a string.So in your case you only have a single ' ' in the array, meaning the other 11 characters will be taken from whatever follows
arrayChars
in memory.If you want to print out a pattern of n spaces, the easiest way to do that would be to use
-(NSString *)stringByPaddingToLength:withString:startingAtIndex:
, i.e creating something like this.The
stringWithCharaters:length:
method makes anNSString
(or an instance of a subclass ofNSString
) using the first length characters in the C array. It does not iterate over the given array of characters until it reaches the length.The output you are seeing is the area of memory 12 Unicode characters long starting at the location of your passed 1 Unicode character array.
This should work.