Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace certain words in a sentence

Tags:

java

android

I'm developing an app in Android Studio that translates certain words that I've made up myself. I've got the part in the code that translates the words right, but it only works when I type in the word but not when I type the word in a sentence. When I type in the sentence, it does not display anything when I press the button. For example: When I type in "Cookie", I get "Biscuit". But when I type in "I love me a Cookie", it does not display the sentence and the word when I press the button.

This is my code so far:

public class MainActivity extends AppCompatActivity {
    EditText mType;
    Button mSearch;
    TextView mResults;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mType = (EditText) findViewById(R.id.typeWordTxt);
        mSearch = (Button) findViewById(R.id.find8tn);
        mResults = (TextView) findViewById(R.id.resultsTxt);
        mSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mType.getText().toString().trim().equals("cookie"))
                {
                    mResults.setText("biscuit");
                }
            }
        });
    }
}
like image 494
CFOJOLT Avatar asked Mar 13 '26 05:03

CFOJOLT


1 Answers

You can do it like this:

if (mType.getText().toString().toLowerCase().contains("cookie")) {
    mResults.setText(mType.getText().toString().replaceAll("(?i)cookie", "biscuit"));
}

As @Andreas said to the comment below you can use it to replace if is a whole word and not to replace a string in a word.

like image 112
ddarellis Avatar answered Mar 14 '26 20:03

ddarellis