Replace # with \u0023 in a Java String - java

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.

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

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");

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");

Related

How to find and replace '[' in a String?

i am having a String "['MET', 'MISSED']". Here i want to replace "[ to [ and ]" to ]. I have used the escape sequences in my String like
wkJsonStr.replaceAll("\"\\[","[");
and
wkJsonStr.replaceAll("\\]\"","]");
but none of the above worked. In 'watch' i edited like
wkJsonStr.replaceAll("\"[","[");
and it worked. But in my Android Studio Editor this Expression is not allowed. I am getting "Unclosed character class".
I am expecting my String after replacing to be like ['MET', 'MISSED']. I want to remove the first and last quotation alone and i would like to achieve it by replaceAll method.
Remember that string are immutable in java...
just calling the replace method will take no effect, you need to assign the return value, otherwise will get lost.
Example:
public static void main(String[] args) {
String wkJsonStr = "\"['MET', 'MISSED']\"";
System.out.println(wkJsonStr);
wkJsonStr = wkJsonStr.replaceAll("\"\\[", "[").replaceAll("\\]\"", "]");
System.out.println(wkJsonStr);
}
this will print.
"['MET', 'MISSED']"
['MET', 'MISSED']
You can use replace instead of replaceAll, but if you really need to use replaceAll then you can do:
wkJsonStr.replaceAll("\"\\Q[\\E","[").replaceAll("\\Q]\\E\"","]")
Here,
\" literally denotes "
The part between \\Q and \\E is literally treated., i.e,
\\Q[\\E denotes [
\\Q]\\E denotes ]
I agree with #Wiktor Stribiżew's comment. And you should declare your String like this:
String str = "\"['MET', 'MISSED']\""; // like this your editor will not give an error
str = str.replace("\"[","[");
str = str.replace("]\"","]");
textview.setText(str);
I finally realized that the isssue is not with the Regex character. Its the Variable which i am using. when i am replacing one by one it is not forwarding the result to the next step. So i have assigned the value to a variable and now its working.
String firstResult = wkJsonStr.replaceAll("\"\\[","[");
and
String result = firstResult.replaceAll("\\]\"","]");
is working for me. Or This step will do a trick.
String result= wkJsonStr.replaceAll("\"\\[","[").replaceAll("\\]\"","]");

How can I remove " ' " from a String

I tried:
mystring.replace("'","");
and also
mystring.replaceAll("[']","");
But none of them work, please show me how to remove that ' from my string.
Are you assinging the result of this method? You should be calling it like this :
mystring = mystring.replace("'","");
Strings in Java are immutable - when you call replace, it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want:
This is why you have to assign the return value to a string.
As a note, this also applies to all methods in String. Methods like toUpperCase() return the new string. It does not change the existing.
First, for better help faster please post an MCVE. Next, Java String is immutable, so you must update the mystring reference. Something like,
String mystring = "Papa John's";
mystring = mystring.replace("'","");
System.out.println(mystring);
Output is (as requested) without '
Papa Johns

Replace String variable with exact string

If i want to replace one string variable with exact string in java, what can I do?
I know that replace in java , replace one exact string with another, but now i have string variable and i want to replace it's content with another exact string.
for example:
`String str="abcd";
String rep="cd";`
Now I want to replace rep content with"kj"
It means that I want to have str="abkj" at last.
If I understand your question, you could use String.replace(CharSequence, CharSequence) like
String str="abcd";
String rep="cd";
String nv = "kj";
str = str.replace(rep, nv); // <-- old, new
System.out.println(str);
Output is (the requested)
abkj
i think he wants:
String toReplace = "REPLACE_ME";
"REPLACE_ME What a nice day!".replace(toReplace,"");
"REPLACEME What a nice day!".replace(toReplace,"") results in:
" What a nice day!"

Android - how to replace part of a string by another string?

I have strings with some numbers and english words and I need to translate them to my mother tongue by finding them and replacing them by locallized version of this word. Do you know how to easily achieve replacing words in a string?
Thanks
Edit:
I have tried (part of a string "to" should be replaced by "xyz"):
string.replace("to", "xyz")
But it is not working...
It is working, but it wont modify the caller object, but returning a new String.
So you just need to assign it to a new String variable, or to itself:
string = string.replace("to", "xyz");
or
String newString = string.replace("to", "xyz");
API Docs
public String replace (CharSequence target, CharSequence replacement)
Since: API Level 1
Copies this string replacing
occurrences of the specified target
sequence with another sequence. The
string is processed from the beginning
to the end.
Parameters
target the sequence to replace.
replacement the replacement
sequence.
Returns the resulting string.
Throws NullPointerException if target or replacement is null.
MAY BE INTERESTING TO YOU:
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
In kotlin there is no replaceAll, so I created this loop to replace repeated values ​​in a string or any variable.
var someValue = "https://www.google.com.br/"
while (someValue.contains(".")) {
someValue = someValue.replace(".", "")
}
Log.d("newValue :", someValue)
// in that case the stitches have been removed
//https://wwwgooglecombr/
String str = "to";
str.replace("to", "xyz");
Just try it :)
rekaszeru
I noticed that you commented in 2011 but i thought i should post this answer anyway, in case anyone needs to "replace the original string" and runs into this answer ..
Im using a EditText as an example
// GIVE TARGET TEXT BOX A NAME
EditText textbox = (EditText) findViewById(R.id.your_textboxID);
// STRING TO REPLACE
String oldText = "hello"
String newText = "Hi";
String textBoxText = textbox.getText().toString();
// REPLACE STRINGS WITH RETURNED STRINGS
String returnedString = textBoxText.replace( oldText, newText );
// USE RETURNED STRINGS TO REPLACE NEW STRING INSIDE TEXTBOX
textbox.setText(returnedString);
This is untested, but it's just an example of using the returned string to replace the original layouts string with setText() !
Obviously this example requires that you have a EditText with the ID set to your_textboxID
You're doing only one mistake.
use replaceAll() function over there.
e.g.
String str = "Hi";
String str1 = "hello";
str.replaceAll( str, str1 );

Replacing characters in Java

I tried to replace characters in String which works sometimes and does not work most of the time.
I tried the following:
String t = "[javatag]";
String t1 = t;
String t2 = t;
t.replace("\u005B", "");
t.replace("\u005D", "");
t1.replace("[", "");
t1.replace("]", "");
t2.replace("\\]", "");
t2.replace("\\[", "");
System.out.println(t+" , "+t1+" , "+t2);
The resulting output is still "[javatag] , [javatag] , [javatag]" without the "[" and "]" being replaced.
What should I do to replace those "[" and "]" characters ?
String objects in java are immutable. You can't change them.
You need:
t2 = t2.replace("\\]", "");
replace() returns a new String object.
Edit: Because ... I'm breaking away from the pack
And since this is the case, the argument is actually a regex, and you want to get rid of both brackets, you can use replaceAll() instead of two operations:
t2 = t2.replaceAll("[\\[\\]]", "");
This would get rid of both opening and closing brackets in one fell swoop.
Strings are immutable so
t.replace(....);
does nothing
you need to assign the output to some variable like
t = t.replace(....);
Strings in Java are immutable, meaning you can't change them. Instead, do t1 = t1.replace("]", "");. This will assign the result of replace to t1.
String.replace doesn't work that way. You have to use something like t = t.replace("t", "")
String.replace() returns a new string after replacing the required characters. Hence you need to do it in this way:
String t = "[javatag]";
t = t.replace("[","");
t = t.replace("]","");
t.replace(....);
gives you a String (return a string)
you can reassign the origin variable name to the new string
and the old string will later been garbage-collected
:)

Categories