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...
To replace one string with another string using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.
text = text. replaceAll("[*]",""); // OR text = text. replaceAll("\\*","");
You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement. The following example removes all commas from a string.
Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With