简体   繁体   中英

Java Replace specific number in String using .replace(x,y)?

Is it possible to replace a specific number in a String by using:

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

I have tried doing this, and it does not seem to work. Is there a dynamic way to do this that lets me use an Integer?

Here is the code:

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

When I print it, I get something like this:

10014001261627161

It works fine, in all forms.

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) + "\"");
}

Output is:

"" -> "" = "" = ""
"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"

You need to cast the int to a String , as String.replace() expects either a char or a CharSequence (which is a superclass of String ). It will not accept an int argument.

The most explicit way to do what you are asking is to cast using Integer.toString() . Like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM