Localization with string.Format

旧时模样 提交于 2020-01-04 02:44:07

问题


Currently I am mostly doing the localization by putting key-value pairs into a Resources.resw file. So I wonder about how I should localize strings that need formatting or say strings with different grammar orders in different languages. It might be easier to understand what I mean with the examples below.

For example, just as this part in the official document for localization suggests, one language can have the date format of

string.Format("Every {0} {1}", monthName, dayNumber);

while the other uses

string.Format("Every {1} {0}", monthName, dayNumber);

In this situation, what is the best way to localize such a string?

Things/Grammars can be way more complicated than this example. The suggestion in the official document doesn't look good to me because a date can be unpredictable. Or may be you can enumerate the date, but that requires a lot of work. Or let's say we have a string that takes user input, like

 string.Format("Do you want to delete {name}?", name);

In another language it might have this grammar order

string.Format("You want to delete {name} do?", name);

It is impossible to localize the whole sentence as the example suggests in the document.

The only way of avoiding situation that I can think of is not to put user input....


回答1:


If you have access to the date you could use The Month ("M", "m") Format Specifier

From the documentation:

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("m", 
                  CultureInfo.CreateSpecificCulture("en-us")));
// Displays April 10                        
Console.WriteLine(date1.ToString("m", 
                  CultureInfo.CreateSpecificCulture("ms-MY")));
// Displays 10 April

For string.Format("Do you want to delete {name}?", name); you can

$"Do you want to delete the following user? '{name}'";



回答2:


One way I just found out is to put this key-value pair into the Resources.resw:

Key: RemoveText

Value: Do you want to delete {0}?

After you get the localized string like doing

var msg = Localize('RemoveText');

Then

var result = string.Format(msg, name)

can give you the expected result.

Basically, you need to put {0} appropriately in every language. The only flaw of this solution is that {0} should not be allowed in the user input.

If you still want {0} to appear, you can change {0} to other strings that you think are too complicated and long for user to type in, for example '{usersAreVeryUnlikelyToTypeInThisInTheirInputs}'. And then use

msg.replace('{usersAreVeryUnlikelyToTypeInThisInTheirInputs}', name)

to get the localized string.



来源:https://stackoverflow.com/questions/58443767/localization-with-string-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!