Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a character by another character in a string in android?

Simply i want to replace a character with another in android.. My code:

et = (EditText) findViewById(R.id.editText1);
String str = et.getText().toString();
str.replace(' ','_');
et.setText(str);
System.out.println(str);

But here the "space" is not replaced by "underscore".. I also tried other character too..

please help!!

like image 269
prg Avatar asked Nov 18 '11 08:11

prg


People also ask

How do you change special characters on Android?

static String replaceString(String string) { return string. replaceAll("[^A-Za-z0-9 ]","");// removing all special character. } this is work great but if user will enter the other language instead of eng then this code will replace the char of other language.

Can we use Replace function to replace character with another character in a string variable?

String Replace() Method As the name itself suggests, the replace() method is used to replace all the occurrences of a specific character of a String with a new character.


3 Answers

Strings are immutable in Java - replace doesn't change the existing string, it returns a new one. You want:

str = str.replace(' ','_');

(This is definitely a duplicate, but I don't have enough time right now to find an appropriate one...)

like image 192
Jon Skeet Avatar answered Oct 23 '22 21:10

Jon Skeet


String is immutable and you cannot change it. So, you need to do this:

str = str.replace(' ','_');
like image 23
Eng.Fouad Avatar answered Oct 23 '22 21:10

Eng.Fouad


See code:

et = (EditText) findViewById(R.id.editText1);
String str = et.getText().toString();
str = str.replace(' ', '_');
System.out.println(str);
like image 40
shoeab Avatar answered Oct 23 '22 21:10

shoeab