[英]Java on-the-fly string replacement
我在代碼中看到了類似的東西
somestring = "Today is {0}, tomorrow is {1}";
我知道它將把另一個變量的值放入字符串中,但是我該怎么做呢?
更新 :由於有幾種方法可以達到這種效果,哪種方法最有效?
您是否看過MessageFormat文檔?
例如(一個例子)
Object[] arguments = {
new Integer(7),
new Date(System.currentTimeMillis()),
"a disturbance in the Force"
};
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
arguments);
output: At 12:30 PM on Jul 3, 2053, there was a disturbance
in the Force on planet 7.
關於你的問題。 效率,如果您遇到性能問題並且與此有關,我只會擔心。 我希望上述方法是相當有效的-尤其是考慮到可能會涉及一些輸出(達到標准輸出或類似的輸出?),我希望這是一個更大的瓶頸。
// Assuming variables today and tomorrow are strings.
somestring = String.format("Today is %s, tomorrow is %s", today, tomorrow);
您可以使用java.text.MessageFormat類
我認為您的示例專門使用java.text.MessageFormat。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.