在Objective-C中,如何打印N个空格? (使用stringWithCharacters) [英] In Objective-C, how to print out N spaces? (using stringWithCharacters)

查看:183
本文介绍了在Objective-C中,如何打印N个空格? (使用stringWithCharacters)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

推荐答案

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

You can use %*s to specify the width.

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

参考:


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

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.

这篇关于在Objective-C中,如何打印N个空格? (使用stringWithCharacters)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆