Java使用.replace(x,y)替换String中的特定数字?

时间:2015-08-19 01:51:26

标签: java string

是否可以使用以下命令替换String中的特定数字:

c:\> RunDLL32.exe URLMon.dll,URLDownloadToFIle 0,"http://www.example.com/file.pdf" "c:\\MyName\\Downloads\\",0

我尝试过这样做,但似乎没有用。有没有动态的方法可以让我使用整数?

以下是代码:

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

当我打印它时,我得到这样的东西:

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);
}

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分:0)

您需要将int转换为String,因为String.replace()需要charCharSequenceString的超类int 1}})。 接受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); } 进行投射。像这样:

template: '<a href="{{ link }}" target="_blank"><img src="{{ image }}" /><div class="likes">&hearts; {{ likes }}</div></a>'