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

前端 未结 6 849
夕颜
夕颜 2020-11-27 17:07

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

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 17:47

    rekaszeru

    I noticed that you commented in 2011 but i thought i should post this answer anyway, in case anyone needs to "replace the original string" and runs into this answer ..

    Im using a EditText as an example


    // GIVE TARGET TEXT BOX A NAME

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

    // STRING TO REPLACE

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

    // REPLACE STRINGS WITH RETURNED STRINGS

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

    // USE RETURNED STRINGS TO REPLACE NEW STRING INSIDE TEXTBOX

    textbox.setText(returnedString);
    

    This is untested, but it's just an example of using the returned string to replace the original layouts string with setText() !

    Obviously this example requires that you have a EditText with the ID set to your_textboxID

提交回复
热议问题