Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert backslash into my string in java?

Tags:

java

string

I have string, and I want to replace one of its character with backslash \

I tried the following, but no luck.

engData.replace("'t", "\\'t")

and

engData = engData.replace("'t", String.copyValueOf(new char[]{'\\', 't'}));

INPUT : "can't"

EXPECTED OUTPUT : "can\'t"

Any idea how to do this?

like image 620
AndroidDev Avatar asked Dec 12 '22 09:12

AndroidDev


2 Answers

Try this..

    String s = "can't";
    s = s.replaceAll("'","\\\\'");
    System.out.println(s);

out put :

    can\'t

This will replace every ' occurences with \' in your string.

like image 100
prime Avatar answered Dec 13 '22 23:12

prime


Try like this

engData.replace("'", "\\\'");

INPUT : can't

EXPECTED OUTPUT : can\'t

like image 20
Amit Gupta Avatar answered Dec 13 '22 23:12

Amit Gupta