ios 如何使用格式化占位符本地化字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4881628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I localize a string with formatting placeholders?
提问by Moshe
How do I localize a string that has placeholders in it with NSLocalizedString?
如何使用 NSLocalizedString 本地化包含占位符的字符串?
For example:
例如:
[NSString stringWithFormat:@"You can afford %i at %@%li.",[kCash integerValue]/self.price, kYen, self.price]
How do I localize this? Do I do break up the strings into multiple localized strings? How then do I deal with varying sentence structure and grammar?
我如何本地化这个?我是否将字符串分解为多个本地化字符串?那么我如何处理不同的句子结构和语法?
采纳答案by Matti Virkkunen
Have the localized strings include the placeholders. That's pretty much the only proper way to do it as otherwise, as you mentioned, you couldn't take varying word order into account.
让本地化的字符串包含占位符。这几乎是唯一正确的方法,否则,正如您所提到的,您无法考虑不同的词序。
Something along these lines:
沿着这些路线的东西:
[NSString stringWithFormat:NSLocalizedString(@"Foo %i", @"Foo %i"), 123]
回答by Alan Rowarth
NSLocalizedString won't alter your placeholders, so stringWithFormat can use them as normal. In your example, using numbered placeholders is probably a good idea -
NSLocalizedString 不会改变你的占位符,所以 stringWithFormat 可以正常使用它们。在您的示例中,使用编号占位符可能是一个好主意-
[NSString stringWithFormat:@"You can afford %1$i at %2$@%3$li.",
[kCash integerValue]/self.price, kYen, self.price]
More info here: Is there a way to specify argument position/index in NSString stringWithFormat?
回答by Chris
Another approach to this is in your localized file, you can have:
另一种方法是在您的本地化文件中,您可以:
key = "String with %@ placeholder";
and in your implementation:
并在您的实施中:
[NSString stringWithFormat: NSLocalizedString(@"key", ""), @"string replacing placeholder"];
You can do this with any number of arguments, they just need to be consistent across your localization files.
您可以使用任意数量的参数执行此操作,它们只需要在您的本地化文件中保持一致。
回答by Umit Kaya
This way seems more efficient:
这种方式似乎更有效:
[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Key", @"Comment for localised string"), value];