41

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 strings into multiple localized strings? How then do I deal with varying sentence structure and grammar?

Moshe
  • 57,511
  • 78
  • 272
  • 425

4 Answers4

51

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?

Community
  • 1
  • 1
Alan Rowarth
  • 2,250
  • 2
  • 14
  • 10
21

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]
Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • Will this work though? Will NSLocalizedString know about the placeholders and not consider them to be arbitrary text? – Moshe Feb 03 '11 at 00:49
  • 3
    This will work for one argument, but if you have two arguments then in many languages you will also want to change the order which the placeholders appear. – Nik Reiman Jun 22 '11 at 07:11
  • 21
    -1 This code will not work for text that is order sensitive. It should instead use the positional arguments (ex. %1$@). Also, the second parameter of NSLocalizedString is intended to be a comment to the translators to better understand the context of the text being translated. Repeating the initial text is meaningless, especially with formatter strings. – rbrown Oct 31 '12 at 19:53
  • Fine, fine, downvotes. I'd delete it if it wasn't the accepted answer! You can't delete those yourself. – Matti Virkkunen Aug 19 '14 at 23:42
  • For more complex formatting, such as date formats, see this: 'NSString stringWithFormat(NSLocalizedString(@"%1$02dh %2$02dm %3$02ds","") 1,2,3);' will give you "01h 02m 03s" for example. – Anna Billstrom Sep 03 '14 at 15:35
9

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.

Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
Chris
  • 7,270
  • 19
  • 66
  • 110
1

This way seems more efficient:

[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Key", @"Comment for localised string"), value];
Umit Kaya
  • 5,771
  • 3
  • 38
  • 52