android/java中抓取一个词

在句子中找出一个词,比如用户输入了 "My friend is a cowboy"。应用就能根据数组检测出 cowboy。

String[] words = {"cowboy", "animal", "monster"};

代码:

 String[] words = {"cowboy", "animal", "monster"};
Boolean b;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    text = (EditText) findViewById (R.id.editText1);
    view = (TextView) findViewById (R.id.textView1);

    ok = (Button) findViewById (R.id.button1);
    ok.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String string = text.getText().toString();
            b = string.indexOf("cowboy") > 0;
            view.setText(b.toString());
        }
    });

}

但是给出的结果不对。

String[] words = {"cowboy", "animal", "monster"};
String s = "My friend is a Cowboy";
boolean check = false;

for (int i = 0; i < words.length; i++) {
    if (s.toLowerCase().contains(words[i].toLowerCase())) {
        check = true;
    } else {

    }
}
if (check) {
     System.out.println("Yes");
} else {
     System.out.println("No");
}

试了一下,你的代码并无错误