Java - String replace exact word

前端 未结 6 1209
难免孤独
难免孤独 2020-12-14 07:26
String x = \"axe pickaxe\";
x = x.replace(\"axe\", \"sword\");
System.out.print(x);

By this code, I am trying to replace the exact word axe

6条回答
  •  余生分开走
    2020-12-14 08:08

    If you only want to replace the first occurrence, there is a method replaceFirst in String object.

    String x = "axe pickaxe";
    x = x.replaceFirst("axe", "sword");
    System.out.print(x); //returns sword pickaxe
    

提交回复
热议问题