您的位置:首页 > 移动开发 > Objective-C

字符串格式化占位符

2014-04-09 17:08 246 查看


字符串格式化占位符

这篇文章总结nsstring format 支持的格式占位符


格式化占位符

NSString 和 CFString 支持格式化占位符和IEEE printf占位符一样 如表1所示。
注意:可以使用“n$”位置定位符,例如%1$@, %2$s.
此方法经常用于国际化,用于本地化语言的顺序不同,需要调换参数位置。如:
中文:“do %s , %s” = "%2$s做%1$s";
英文:“do %s , %s” = “do %1$s ,
%2$s!”;

NSLocalizedString(@"do %s , %s", @"sth", @"please");
输出:中文:please做sth
  英文:do sth, please!

表 1 NSString 和 CFString 格式化方法支持的占位符
占位符                                   
说明
%@

Objective-C 对象,如果对象拥有descriptionWithLocale:方法则调用这个方法返回的值,否则的话输出description返回的值;
CFTypeRef对象,输出CFCopyDescription的返回值
%%

输出‘%’字符

%d
%D

有符号的32位整型(int)
%u
%U

无符号的32位整型 (
unsigned int
).
%x

无符号的32位整型 (
unsigned int
), 以十六进制格式小写输出
%X

无符号的32位整型 (
unsigned
int
), 以十六进制格式大写输出
%o
%O

无符号的32位整型 (
unsigned
int
), 以八进制格式输出
%f

64位双精度浮点型 (
double
).
%e

64位双精度浮点型 (
double
), 以指数格式使用小写e指数
%E

64位双精度浮点型 (
double
),
以指数格式使用大写e指数
%g

64位双精度浮点型  (
double
), 自动处理,如果指数小于-4或大于等于精度,按照%e格式输出,否则按照%f输出
%G

64位双精度浮点型  (
double
),
自动处理,如果指数小于-4或大于等于精度,按照%E格式输出,否则按照%f输出
%c

8位无符号字符,NSLog以ASCII格式打印出,如果不是ASCII字符,使用\\ddd八进制或者Unicode十六进制\\udddd, 'd'是数字
%C

16位无符号字符,NSLog以ASCII格式打印出,如果不是ASCII字符,使用\\ddd八进制或者Unicode十六进制\\udddd, 'd'是数字
%s

以null结尾的8位Unicode字符串

%S

以null结尾的16位Unicode字符串
%p

void指针,以0x开头的十六进制格式输出
%a

64位浮点数(double),以0x开头,在小数点前有一个十六进制,使用小写p的指数
%A

64位浮点数(double),以0X开头,在小数点前有一个十六进制,使用大写p的指数
%F

64位浮点数
Table 2  NSString和cfstring格式化函数支持的长度修饰符
Length modifier
Description
h

Length modifier specifying that a following 
d
o
u
x
,
or 
X
 conversion specifier applies to a 
short
 or 
unsigned
short
 argument.
hh

Length modifier specifying that a following 
d
o
u
x
,
or 
X
 conversion specifier applies to a 
signed char
 or 
unsigned
char
 argument.
l

Length modifier specifying that a following 
d
o
u
x
,
or 
X
 conversion specifier applies to a 
long
 or 
unsigned
long
 argument.
ll
q

Length modifiers specifying that a following 
d
o
u
x
,
or 
X
 conversion specifier applies to a 
long long
 or 
unsigned
long long
 argument.
L

Length modifier specifying that a following 
a
A
e
E
f
F
g
,
or 
G
 conversion specifier applies to a 
long double
 argument.
z

Length modifier specifying that a following 
d
o
u
x
,
or 
X
 conversion specifier applies to a 
size_t
 or the corresponding signed integer type argument.
t

Length modifier specifying that a following 
d
o
u
x
,
or 
X
 conversion specifier applies to a 
ptrdiff_t
 or the corresponding unsigned integer type
argument.
j

Length modifier specifying that a following 
d
o
u
x
,
or 
X
 conversion specifier applies to a 
intmax_t
 or 
uintmax_t
 argument.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息