Question: Replace certain words in a sentence

Question

Replace certain words in a sentence

Answers 3
Added at 2016-12-30 20:12
Tags
Question

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");
                }
            }
        });
    }
}
Answers
nr: #1 dodano: 2016-12-30 20:12

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.

nr: #2 dodano: 2016-12-30 20:12

It's a simple task you can do the below

String str = "abc";
str.replace("abc", "xyz");

It will replace the word to with xyz in the whole string. Try it an d let me know that is this what you want

nr: #3 dodano: 2016-12-30 20:12

Because you use equals, for finding word from sentence you must use method contains() and replaceAll() for replace all of this words

Source Show
◀ Wstecz