字符串格式化技巧/文档 [英] String Formatting Tricks/Docs
问题描述
下读书粗野青蛙应对这个帖子,被下面的行$好奇的C $ C:
Was reading the response by Shaggy Frog to this post and was intrigued by the following line of code:
NSLog(@"%@", [NSString stringWithFormat:@"%@:%*s%5.2f", key, padding, " ", [object floatValue]]);
我知道字符串格式化是一种古老的艺术,但我有点做最终绕成可可/的OBJ-C编程和跳了几个档次沿途。哪里是一个很好的(最好)学习的地方所有允许在字符串格式化技巧的NSString的 stringWithFormat
?我熟悉苹果公司的<一个href=\"http://developer.apple.com/mac/library/documentation/cocoa/conceptual/Strings/Articles/formatSpecifiers.html\"相对=nofollow>字符串格式说明页,但我可以告诉它无论是与发生的事情并不揭示%* S
或%5.2f
(更不用说3明显占位符后面4个参数)上面?!?
I know string formatting is an age old art but I'm kinda doing the end around into Cocoa/Obj-C programming and skipped a few grades along the way. Where is a good (best) place to learn all the string formatting tricks allowed in NSString's stringWithFormat
? I'm familiar with Apple's String Format Specifiers page but from what I can tell it doesn't shed light on whatever is happening with %*s
or the %5.2f
(not to mention the 3 apparent placeholders followed by 4 arguments) above?!?
推荐答案
的 -stringWithFormat 的带领您到<一个文档href=\"http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html\"相对=nofollow>字符串格式说明反过来向您发送的的 IEEE的printf规范。这是对尽可能多的信息,你永远想要的。
The documentation of -stringWithFormat leads you to String Format Specifier which in turn sends you to the IEEE printf specification. That's about as much information as you'll ever want.
唯一的例外:
Objective-C的对象,印为
通过字符串返回
的 descriptionWithLocale:的如果有的话,
或说明的其他方式。也适用
用的 CFTypeRef 的对象,返回
的结果的 CFCopyDescription 的
功能。
%@
Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function.
- 的无的被转换成的(空)的,这就是为什么
的NSLog(@%@,someObject)
比的NSLog(someObject)
后来可能崩溃更安全时的 someObject 的是无的:
- nil gets converted to (null), that's the reason why
NSLog(@"%@", someObject)
is safer thanNSLog("someObject)
. The later might crash when someObject is nil:
您可能也有兴趣在维基百科关于字符串格式化页。
这篇关于字符串格式化技巧/文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!