Table of Contents
1. Introduction
In this post, we will learn about how to replace backslash with forward slash in java.
backslash() is used as escape character in Java. For example:
It can be used to:
- Used in special characters such as new line character
\n
, tab\t
- Write unicode characters like
\u%04x
.
That’s the reason we can’t directly replace backslash to forward slash. We need to escape it while replacing it.
Let’s go through different ways to do it.
2. Using replace() Method
Use String’s replace()
method to replace backslash with forward slash in java.
String’s replace()
method returns a string replacing all the CharSequence to CharSequence.
Syntax of replace()
method:
1 2 3 |
public String replace(CharSequence target, CharSequence replacement) |
Here is an example:
1 2 3 4 5 |
String str = "C:\\tempDir\\temp.txt"; str = str.replace("\\","/"); System.out.println(str); |
Output:
As you can see, replace() method replaceed each space with underscore.
3. Using replaceAll()
method
Use replaceAll()
method to replace backslash with forward slash in java. It is identical to replace()
method, but it takes regex as argument.Since the first argument is regex, you need double escape the backslash.
Here is syntax of replaceAll method:
1 2 3 |
public String replaceAll(String regex, String replacement) |
1 2 3 4 5 |
String str = "C:\\tempDir\\temp.txt"; str = str.replaceAll("\\\\","/"); System.out.println(str); |
Output:
Further reading:
That’s all about how to replace backslash with forward slash in java.