objective-c - 本地化串联或动态字符串

标签 objective-c cocoa localization

我熟悉使用 NSLocalizedString() 来本地化字符串,但我今天遇到的问题需要更多的技巧。我的情况是这样的:

NSString *userName; //the users name, entered by the user.  Does not need localized
NSString *favoriteFood; //the users favorite food, also entered by user, and not needing localized

NSString *summary = [NSString stringWithFormat:@"%@'s favorite food is %@", userName, favoriteFood];

这适用于英语,但并非每种语言都使用与英语相同的词序,例如,将同一句子从日语逐字翻译成英语会是:

UserName's favorite food pizza is

更不用说 's is 并不是所有语言中的所有格。

有哪些技术可用于本地化此类连接句?

为了他人的利益而更新: @Jon Reed 是对的,位置说明符对于本地化非常重要。他链接的文档仅包含对它们可以与 NSString、NSLog 等一起使用这一事实的引用,该链接并没有真正说明如何使用它们。

我找到了 this link ,这很好解释。它也比我更好地解释了我的问题。来自链接:

Format strings for printf and sprintf (see Printf) present a special problem for translation. Consider the following:1

 printf(_"String `%s' has %d characters\n",
           string, length(string))) A possible German

translation for this might be:

 "%d Zeichen lang ist die Zeichenkette `%s'\n" The problem

should be obvious: the order of the format specifications is different from the original! Even though gettext can return the translated string at runtime, it cannot change the argument order in the call to printf.

To solve this problem, printf format specifiers may have an additional optional element, which we call a positional specifier. For example:

 "%2$d Zeichen lang ist die Zeichenkette `%1$s'\n" Here, the

positional specifier consists of an integer count, which indicates which argument to use, and a ‘$’. Counts are one-based, and the format string itself is not included. Thus, in the following example, ‘string’ is the first argument and ‘length(string)’ is the second:

 $ gawk 'BEGIN {
 >     string = "Dont Panic"
 >     printf _"%2$d characters live in \"%1$s\"\n",
 >                         string, length(string)
 > }'
 -| 10 characters live in "Dont Panic"

最佳答案

要指定替换顺序,请使用 %1$@%2$@ 作为您的格式说明符。本地化格式字符串可以按任何顺序使用它们。例如,假设您的字符串键是“FavoriteFood”。调用

NSString *summary =
            [NSString stringWithFormat:NSLocalizedString(@"FavoriteFood", nil), 
                                       userName, favoriteFood];

本地化将格式说明符放在对其语言环境有意义的地方。示例:

"FavoriteFood" = "%2$@ is the favorite food of %1$@";

参见 String Format Specifiers

关于objective-c - 本地化串联或动态字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2459390/

相关文章:

objective-c - 拖动调整 NSView(或其他对象)的大小

asp.net-mvc - 为 dnx rc2 运行 MVC 6 ASP.NET 5 本地化示例

c# - Nopcommerce - 本地化资源缺失

iphone - 无法使用 __bridge 将 CFStringRef 转换为 NSString

ios - 自定义 uitableviewcell 与文本字段消失

iphone - 如何在 Enter 按键时关闭键盘

objective-c - 变量声明方式的区别

cocoa - +颜色与图案图像 : should preserve transparency in Cocoa

objective-c - 如何从屏幕内容创建 NSImage 实例

php - PoEdit 关键字 - 复数形式