字符串格式化技巧/文档 [英] String Formatting Tricks/Docs

查看:122
本文介绍了字符串格式化技巧/文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在阅读Shaggy Frog对此信息的回复,并对以下代码段感兴趣:

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

我知道字符串格式化是一个古老的艺术,但我有点结尾到Cocoa / Obj-C编程,并跳过了几个等级沿途。在哪里可以学习NSString的 stringWithFormat 中允许的所有字符串格式化技巧?我熟悉Apple的字符串格式说明符页面,但从我可以告诉它没有阐明发生在%* 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 的文档导致您访问字符串格式说明符,它会将您发送到 IEEE printf specification

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.

唯一值得注意的例外情况:

The only notable exception:


%@



Objective-C对象,以
返回的
字符串打印 descriptionWithLocale: if可用,
描述。还可以通过 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.


  • 会转换为(null),这就是为什么 NSLog(someObject)。NSLog(@%@,someObject) nil

  • nil gets converted to (null), that's the reason why NSLog(@"%@", someObject) is safer than NSLog("someObject). The later might crash when someObject is nil:
  • 您可能还对 wikipedia page about string formatting

    这篇关于字符串格式化技巧/文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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