在Java中使用String.format而不是字符串连接是更好的做法吗? [英] Is it better practice to use String.format over string Concatenation in Java?

查看:160
本文介绍了在Java中使用String.format而不是字符串连接是更好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中使用 String.Format 和字符串连接之间是否存在明显差异?

Is there a perceptible difference between using String.Format and string concatenation in Java?

我倾向于使用 String.format 但偶尔会滑倒并使用concat。我想知道一个人是否比另一个好。

I tend to use String.format but occasionally will slip and use a concat. I was wondering if one was better than the other.

我看到的方式, String.Format 给你格式化字符串的能力更强;和连接意味着您不必担心意外地增加额外的%s或丢失一个%s。

The way I see it, String.Format gives you more power in "formatting" the string; and concatenation means you don't have to worry about accidentally putting in an extra %s or missing one out.

String.format 也更短。

哪一个更具可读性取决于你的头部如何工作。

Which one is more readable depends on how your head works.

推荐答案

我建议最好使用 String.format()。主要原因是 String.format()可以更容易地使用从资源文件加载的文本进行本地化,而连接无法在不生成具有不同代码的新可执行文件的情况下进行本地化每种语言。

I'd suggest that it is better practice to use String.format(). The main reason is that String.format() can be more easily localised with text loaded from resource files whereas concatenation can't be localised without producing a new executable with different code for each language.

如果你计划你的应用程序是可本地化的,你也应该养成为你的格式标记指定参数位置的习惯:

If you plan on your app being localisable you should also get into the habit of specifying argument positions for your format tokens as well:

"Hello %1$s the time is %2$t"

这可以进行本地化,并且可以交换名称和时间令牌,而无需重新编译可执行文件以考虑不同的顺序。使用参数位置,您也可以重复使用相同的参数而不将其传递给函数两次:

This can then be localised and have the name and time tokens swapped without requiring a recompile of the executable to account for the different ordering. With argument positions you can also re-use the same argument without passing it into the function twice:

String.format("Hello %1$s, your name is %1$s and the time is %2$t", name, time)

这篇关于在Java中使用String.format而不是字符串连接是更好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆