Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 274
Moshe Avatar asked Feb 03 '11 00:02

Moshe


People also ask

What does it mean to localize a string?

An unique identifier is attached to each translated string called the "Localization Identifier". It is used to search the dictionaries and locate the value of the string in different languages.

How do you localize a string in Swift?

Select the project and under “Localizations”, click the “+” icon. Add any language you want (I selected Italian) then click on “Finish”. Now go back to Localizable. string file, select it and on the File Inspector (right menu) select “Localize”.


2 Answers

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?

like image 185
Alan Rowarth Avatar answered Oct 09 '22 08:10

Alan Rowarth


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] 
like image 39
Matti Virkkunen Avatar answered Oct 09 '22 08:10

Matti Virkkunen