Replace # with \u0023 in a Java String

2019-09-17 15:38发布

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.

3条回答
我想做一个坏孩纸
2楼-- · 2019-09-17 15:51

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");
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-09-17 16:00

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
查看更多
可以哭但决不认输i
4楼-- · 2019-09-17 16:00

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");
查看更多
登录 后发表回答