Java – Replaces certain words in sentences

Replaces certain words in sentences… here is a solution to the problem.

Replaces certain words in sentences

I’m working on an app in Android Studio to translate certain words that I made up myself. I found the part of the code that translates the word correctly, but it only works when I type the word, not when I enter the word in the sentence. When I type a sentence, it doesn’t show anything when I press the button. For example: When I enter “Cookie”, I get “Biscuit”. But when I enter “I love me a cookie”, it does not display sentences and words when I press the button.

So far, here’s my code:

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");
                }
            }
        });
    }
}

Solution

You can do this:

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

As @Andreas says in the comments below, if it’s a complete word, you can use it to replace, not replace the string in the word.

Related Problems and Solutions