我見過的代碼對Java即時字符串替換
somestring = "Today is {0}, tomorrow is {1}";
我知道,它會把值轉換成字符串從另一個變量這樣的事情,但我怎麼辦呢?
更新:有幾種方法可以達到這種效果,哪種方式最有效?
我見過的代碼對Java即時字符串替換
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.
關於你的問題re。效率,如果遇到性能問題並且與此相關,我只會擔心這一點。我期望上述內容具有相當的效率 - 特別是考慮到可能會有一些輸出(涉及標準輸出或類似輸入),我認爲這會是一個更大的瓶頸。
// Assuming variables today and tomorrow are strings.
somestring = String.format("Today is %s, tomorrow is %s", today, tomorrow);
你可以使用java.text.MessageFormat類所
我覺得你的例子特別使用java.text.MessageFormat。
如果我從.properties文件中獲取第一個字符串,這個工作會嗎? –
第一個字符串來自哪裏並不重要,只要它的字符串是一樣的。另外,如果你傳遞一個Object,我相信它只會爲該對象調用'toString()'。 – Dave
無論字符串來自哪裏,它都可以工作。 –