How do I localize a string with formatting placeholders?
How do I localize a string that has placeholders in it with 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 开发者_JAVA技巧strings into multiple localized strings? How then do I deal with varying sentence structure and grammar?
NSLocalizedString won't alter your placeholders, so stringWithFormat can use them as normal. In your example, using numbered placeholders is probably a good idea -
[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?
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]
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.
This way seems more efficient:
[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Key", @"Comment for localised string"), value];
精彩评论