Java 8 string replace examples

String replace in java is done by methods:

  • replace() - it's using a normal replace
  • replaceAll() - it's using regular expression

The difference is not that the second one replace all and the first replace only 1 occurrence .

More about regex and strings in java:

Basic string replace in java

Replacing all spaces from string:

  • with @
  • nothing
String string = "Split me please";
System.out.println(string.replace(" ", "@"));
System.out.println(string.replace(" ", ""));

result:

Split@me@please
Splitmeplease

Basic string replace special character in java

Replacing special character in java is done by escaping it by slash '\':

String string = "C:\\dir\\replace";
System.out.println(string.replace("\\", "/"));

result:

C:/dir/replace

Java 8 replaceFirst example

Replacing the first occurrence of something can be done by method replaceFirst:
More information here: replaceFirst

 String string = "C:\\dir\\replace";
System.out.println(string.replaceFirst("\\\\", "/"));

result:

C:/dir\replace

Related Article