2017-05-14 82 views
1

我遇到了問題String.format在android中,我想用我的ID替換{0}。 我這個代碼不工作:Android String格式不起作用

String str = "abc&id={0}"; 
String result = String.format(str, "myId"); 

回答

0

你必須設置你的整數值作爲一個單獨的變量。

String str = "abc&id"; 
int myId = 001; 
String result = str+myId; 
0

試試這個,如果你想要一個以上的ID

String result = String.format("abc&id=%s", "myId"); 

編輯,

String.format("abc&id=%s.id2=%s", "myId1", "myId2"); 
+0

謝謝,但是這個不是我的期望。 例如:String str =「abc&id1 = {0},id2 = {1},...」 –

+0

但是你沒有在你的問題中說出它,我們怎麼知道這一點? –

+0

String.format(「abc&id =%s.id2 =%s」,「myId1」,「myId2」); –

1

我認爲你應該使用替換法,而不是格式。

String str = "abc&id={0}"; 
str.replace("{0}","myId"); 
1

你有2種方法可以做到這一點,你將它們混合:)

1.String格式:

String str = "abc&id=%s";//note the format string appender %s 
String result = String.format(str, "myId"); 

2.Message格式:

String str = "abc&id={0}"; // note the index here, in this case 0 
String result = MessageFormat.format(str, "myId"); 
+0

工作完美。解決問題,謝謝 –

+0

歡迎您!不要忘記接受失敗! –