Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 723
Waypoint Avatar asked Apr 22 '11 10:04

Waypoint


People also ask

How do you replace a part of a string with another string?

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.

How can I replace one character in a string in Android?

text = text. replaceAll("[*]",""); // OR text = text. replaceAll("\\*","");

How do I remove part of a string?

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.

How do you replace a specific character in 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.


1 Answers

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.

like image 93
rekaszeru Avatar answered Oct 17 '22 15:10

rekaszeru