N
N
Neonoviiwolf2018-02-04 18:21:40
Java
Neonoviiwolf, 2018-02-04 18:21:40

How to replace "\" in a string with "\\"?

I saw
somewhere how it's done, but I can't find it
.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
g0rd1, 2018-02-04
@Neonoviiwolf

String s1 = "C:\\1.jpg";
String s2 = s1.replace("\\", "\\\\");

K
Kastian, 2018-02-04
@iSmoke

String s1 = "C:\1.jpg";
String s2 = s1.replaceAll("\", "\\");

D
Dmitry Alexandrov, 2018-02-05
@jamakasi666

The answer has already been given but I will explain the reason. The "\" character is an escape of the next character after it. Those. "\\" will tell the compiler that the next character after "\" will be "\". Therefore, if you need to replace a single "\" with a double one, you need to escape each "\" , for this it will be "\\" after which only one "\" will remain, and for a double there are already 4 characters "\\\\" of which the first and 3rd will be discarded screen leaving two "\\" .
There are also control characters:
\n - line break
\t - tab (as if you pressed the tab button, i.e. a large space)
\Q character set \E - the same as the usual "\" but escapes all the content between \Q and \E
And another big list.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question