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

I have strings with some numbers and English words, and I need to translate them into my native language, finding them and replacing them with a localized version of this word. Do you know how easy it is to replace words in a string?

thank

Edit:

I tried (part of the "to" line should be replaced with "xyz"):

string.replace("to", "xyz") 

But it does not work ...

+48
java android string
Apr 22 2018-11-11T00:
source share
5 answers

It works, but it does not change the object of the caller, but returns a new line.
So you just need to assign it to a new String variable or to yourself:

 string = string.replace("to", "xyz"); 

or

 String newString = string.replace("to", "xyz"); 

API Docs

 public String replace (CharSequence target, CharSequence replacement) 

Starting at: Level 1 API

Copies this line, replacing the occurrences of the specified target sequence with another sequence. the string is processed from the very beginning to the end.

Options

  • target replaced sequence.
  • replacement replacement sequence.

Returns the resulting string.

Throws a NullPointerException if the target or replacement is null.

+155
Apr 22 '11 at 10:17
source share
 String str = "to"; str.replace("to", "xyz"); 

Just try it :)

+2
Sep 26 '16 at 6:17
source share

MAY BE INTERESTING FOR YOU:

In java, string objects are immutable. Immutable simply means immutability or immutability.

After creating a string object, its data or state cannot be changed, but a new string object is created.

+1
Nov 22 '16 at 23:54
source share

You make only one mistake.

use the replaceAll() function there.

eg.

 String str = "Hi"; String str1 = "hello"; str.replaceAll( str, str1 ); 
-2
Apr 22 2018-11-11T00:
source share

rekaszeru

I noticed that you commented in 2011, but I thought I should post this answer anyway if someone should β€œreplace the original line” and stumble upon this answer.

I am using EditText as an example




// GIVE THE PURPOSE OF THE TEXT BOX NAME

  EditText textbox = (EditText) findViewById(R.id.your_textboxID); 

// STRING TO REPLACE

  String oldText = "hello" String newText = "Hi"; String textBoxText = textbox.getText().toString(); 

// REPLACE ROWS WITH RETURNED LINES

 String returnedString = textBoxText.replace( oldText, newText ); 

// USE RETURNING STRINGS TO REPLACE A NEW LINE INSIDE A TEXT TEXT

 textbox.setText(returnedString); 

This has not been tested, but this is just an example of using the returned string to replace the original layout string with setText ()!

Obviously, this example requires that you have an EditText with the identifier set for your textaxid

-2
Dec 03 '16 at 3:25
source share



All Articles