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
with sword
. However, if I run this, it prints sword picksword
while I would like to print sword pickaxe
only, as pickaxe
is a different word from axe
although it contains it. How can I fix this? Thanks
To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.
You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement. The following example removes all commas from a string.
Use a regex with word boundaries \b
:
String s = "axe pickaxe"; System.out.println(s.replaceAll("\\baxe\\b", "sword"));
The backslash from the boundary symbol must be escaped, hence the double-backslashes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With