Replace # with \\u0023 in a Java String

2019-09-17 15:51发布

问题:

Replace # with \u0023 in a Java String which looks like below:

{subjectCategory:"s123", subjectId:"111222333", content:"test #comment999", ownerId:"111", ownerName:"tester"}

String.replace("#","\\u0023");

I've tried the above function, but it doesn't seem to work.

回答1:

You need to escape the backslash with another backslash:

string = string.replace("#", "\\u0023");

Test:

String s = "hello # world";
s = s.replace("#","\\u0023");
System.out.println(s); // prints hello \u0023 world


回答2:

Don't forget to assign to a variable:

String toUse = myString.replace("#", "\\u0023");

Probably, you expect to use same string after replace() call. But, strings are immutable, so a new string will be created with replace() call. You need to use it, so use toUse variable.

Note: As said in comments, you can also use old variable again, instead of declaring new one. But ensure to assign result of replace call to it:

myString = myString.replace("#", "\\u0023");


回答3:

You need to apply the replace on the string instance you want to replace, not the static method in String:

myString="test #comment999";
myString.replace("#", "\\u0023");