在Objective-C中,如何打印N个空格?(使用stringWithCharacters)

Jer*_*y L 10 objective-c core-foundation nsstring ios

尝试打印出N个空格(或示例中的12个):

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]);
Run Code Online (Sandbox Code Playgroud)

但他们都打印出奇怪的东西,比如hello ÔÅÓñüÔÅ®Óñü®ÓüÅ®ÓñüÔ®ÓüÔÅ®world...我认为"char数组"和"字符串"相同,而且与"指向字符的指针"相同?API规范说它是一个"Unicode字符的C数组"(通过Unicode,它是UTF8吗?如果是,那么它应该与ASCII兼容)...如何使它工作以及为什么这三种方式赢了干嘛?

Joe*_*Joe 17

您可以使用%*s指定宽度.

NSLog(@"Hello%*sWorld", 12, "");
Run Code Online (Sandbox Code Playgroud)

参考:

字段宽度或精度或两者可以用星号('*')表示.在这种情况下,int类型的参数提供字段宽度或精度.应用程序应确保指定字段宽度或精度或两者的参数在要转换的参数(如果有)之前以该顺序出现.


Ext*_*ire 16

这将为您提供您想要的:

NSLog(@"hello%@world", [@"" stringByPaddingToLength:12 withString:@" " startingAtIndex:0]);
Run Code Online (Sandbox Code Playgroud)

  • @trudyscousin无后顾之忧.还给了你+1的原因我发现downvote有点不公平. (2认同)

Hen*_*mak 6

我认为你遇到的问题是你误解了+(NSString *)stringWithCharacters:length:应该做的事情.它不应该重复字符,而是将它们从数组复制到字符串中.

因此,在您的情况下,您只在数组中有一个'',这意味着其他11个字符将从arrayChars内存中的任何内容中获取.

如果你想打印出n个空格的模式,最简单的方法就是使用-(NSString *)stringByPaddingToLength:withString:startingAtIndex:,即创建这样的东西.

NSString *formatString = @"Hello%@World";
NSString *paddingString = [[NSString string] stringByPaddingToLength: n withString: @" " startingAtIndex: 0];
NSLog(formatString, paddingString);
Run Code Online (Sandbox Code Playgroud)

  • 当然,OP可能更喜欢更抽象的方法以实现可读性和简单性,请记住问题在于理解API的工作原理...... (3认同)