2015-08-19 23 views
0

是否有可能通過替換字符串特定號碼:Java使用.replace(x,y)替換字符串中的特定數字?

string.replace(4 + "", "FOUR"); 

我曾嘗試這樣做,它似乎並沒有工作。有沒有一種動態的方法可以讓我使用Integer?

下面是代碼:

public void generateData(String text) { 
    for (int i = 0; i < array.size(); ++i) { 
     text.replace(array.get(i).number, "HELLO WORLD"); 
    } 
    System.out.println("T: " + text); 
} 

當我打印出來,我得到的是這樣的:

10014001261627161 
+0

你是什麼意思由它不工作?你能給一個樣本輸入和你得到的輸出嗎? – Codebender

+0

您需要將其替換爲字符。如果你不想明確地轉換它,'String.replace(「」+ 4,「FOUR」)應該可以工作。 –

+0

@AaronD,和他已經有什麼不同?我認爲改變這裏的秩序不應該有所作爲。 – Codebender

回答

1

它工作正常,所有形式。

public static void main(String[] args) { 
    test(4, "FOUR", ""); 
    test(4, "FOUR", "Hello"); 
    test(4, "FOUR", "4"); 
    test(4, "FOUR", "1 2 3 4 5 6"); 
    test(4, "FOUR", "123456"); 
    test(4, "FOUR", "Test43"); 
} 
private static void test(int num, String numText, String string) { 
    System.out.println("\"" + string + "\" -> \"" + string.replace(num + "", numText) + "\"" + 
              " = \"" + string.replace("" + num, numText) + "\"" + 
              " = \"" + string.replace(String.valueOf(num), numText) + "\""); 
} 

輸出是:

"" -> "" = "" = "" 
"Hello" -> "Hello" = "Hello" = "Hello" 
"4" -> "FOUR" = "FOUR" = "FOUR" 
"1 2 3 4 5 6" -> "1 2 3 FOUR 5 6" = "1 2 3 FOUR 5 6" = "1 2 3 FOUR 5 6" 
"123456" -> "123FOUR56" = "123FOUR56" = "123FOUR56" 
"Test43" -> "TestFOUR3" = "TestFOUR3" = "TestFOUR3" 
0

您需要的int轉換爲String,作爲String.replace()預計無論是charCharSequence(這是String的超類)。它會不是接受int的說法。

最明確的做法是要使用Integer.toString()進行施法。像這樣:

public void generateData(String text) { 
    for (int i = 0; i < array.size(); ++i) { 
     text=text.replace(Integer.toString(array.get(i).number), "HELLO WORLD"); 
    } 
    System.out.println("T: " + text); 
} 
相關問題