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

耗尽温柔 提交于 2019-12-03 15:44:36

问题


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


回答1:


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




回答2:


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

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



回答3:


See code:

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


来源:https://stackoverflow.com/questions/8179696/replacing-a-character-by-another-character-in-a-string-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!