简体   繁体   中英

Replace certain words in a sentence

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

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.

It's a simple task you can do the below

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

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

因为你使用equals,为了从句子中查找单词,你必须使用方法contains()replaceAll()来替换所有这些单词

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM