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...


Solution 1:

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.

Solution 2:

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.