'How to insert backslash into my string in java?

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?



Solution 1:[1]

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.

Solution 2:[2]

String is immutable in Java. You need to assign back the modified string to itself.

engData = engData.replace("'t", "\\'t"); // assign the modified string back.

Solution 3:[3]

This is possible with regex:

engData = engData.replaceAll("('t)","\\\\$1");

The ( and ) specify a group. The 't will match any string containing 't. Finally, the second part replaced such a string with a backslash character: \\\\ (four because this), and the first group: $1. Thus you are replacing any substring 't with \'t


The same thing is possible without regex, what you tried (see this for output):

engData = engData.replace("'t","\\'t"); //note the assignment; Strings are immutable

See String.replace(CharSequence, CharSequence)

Solution 4:[4]

For String instances you can use, str.replaceAll() will return a new String with the changes requested:

String str = "./";
String s_modified = s.replaceAll("\\./", "");

Solution 5:[5]

The following works for me:

class Foobar {
  public static void main(String[] args) {
    System.err.println("asd\\'t".replaceAll("\\'t", "\\\'t"));
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 prime
Solution 2 Rahul
Solution 3
Solution 4 Vinith
Solution 5