Objective-c 中的转义百分比
我知道 %% 方法,但它不起作用:(。
使用 NSLog
NSLog(@"%%5B hello %%5D");
打印
%5B你好%5D
但带有 NSString
NSString *str = [NSString stringWithFormat:@"%%5B %@ %%5D",@"hello"]; NSLog(str);
打印
5你好68233204
为什么?
I know the %% method, but it's not working :(.
with NSLog
NSLog(@"%%5B hello %%5D");
prints
%5B hello %5D
but with NSString
NSString *str = [NSString stringWithFormat:@"%%5B %@ %%5D",@"hello"]; NSLog(str);
prints
5 hello 68233204
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为你遗漏了一行代码。在您的
stringWithFormat:
版本中,您可能会遇到类似的问题。问题是您现在已经对字符串中的格式字符进行了双重解释。请记住,
NSLog()
和+[NSString stringWithFormat:]
的第一个参数是格式字符串,其中%
字符被特殊处理。在这两种情况下,您可以通过使用实际的格式字符串轻松保留字符串的原始版本(并提前删除重复的 %),如下所示It's because you left out a line of code. In your
stringWithFormat:
version you probably have something likeThe problem is you've now doubly-interpreted format characters in the string. Remember, the first arg to
NSLog()
and to+[NSString stringWithFormat:]
is a format string, where%
characters are treated specially. In both cases, you can easily preserve the original version of the string (and strip out the duplicate %'s ahead of time) by using actual format strings, as in您确实需要使用
stringWithFormat:
如果您不打算传递任何参数,您应该能够只使用但是至于“为什么”,您所遇到的情况正在发生,我不知道当然...尝试传递一个参数,看看它是否仍然发生。也许没有传递参数时存在错误?
根据这篇帖子,您正确地转义了它。
字符串格式说明符文档说你也做得对。
You do need to use
stringWithFormat:
if you aren't going to pass in any arguments, you should be able to just useBut as to "why", what you are experiencing is occurring, I am not sure... Try passing in an argument and see if it still happens. Maybe there is a bug when no arguments are passed?
According to this post you are escaping it correctly.
String format specifiers document says you are doing it right too.