2013-05-30 22 views
-2

示例:我有一個EditText和1個按鈕(onclick:示例)。我想檢查在EditText中輸入的第一個單詞。Android:如何檢查EditText中的字符串?

public void example (View v) { 
    if (edittext.getText().toString() .... //How to check the first word that typed in edittext, 
    ex: if the first word typed in edittext equalsIgnoreCase("a")){ 
     //Action 
}  
+0

而不是按鈕單擊您可以使用TextWatcher。 – SilentKiller

+1

此問題已被詢問。你可以在這裏查看:http://stackoverflow.com/questions/5067942/what-is-the-best-way-to-extract-the-first-word-from-a-string-in-java –

+0

你必須使用onTextChanged事件http://stackoverflow.com/a/6003815/1584654 – GVillani82

回答

2

使用startsWith()

String toCompare = edittext.getText().toString(); 

if (toCompare.startsWith("a")) { 
} 
+2

謝謝,所有的答案正在工作。但這對我來說是最好的方式 – user2341387

1
if(edittext.getText().toString().split(" ")[0].equals("YOUR_STRING")) { 
//DO THE TASK 
} 

隨着空/空的檢查,你可以

if (! TextUtils.isEmpty(editText.getText())) { 
      if ("LOOKING_STRING".equals(editText.getText().toString().split(" ")[0])) { 
       //DO THE TASK HERE 
      } 
     } 
1
String arr[] = edittext.getText().toString().split(" ", 2); 
String firstWord = arr[0]; 
1

試試這個,這將幫助你

  String s=edittext.getText().toString().trim().charAt(0)+"" 

     if(s.equalsIgnoreCase("a")){ 

     give condition 
      } 
1
String s = edittext.getText().toString(); 

if (s.substring(0, s.indexOf(" ")).equalsIgnoreCase("a")) { 
    // do stuff 
} 
1

你也可以使用更快的方式爲你的條件如下:

if (edittext.getText().toString().trim().startsWith("a")) { 
     // here your code when it starts with "a" 
} else { 
    // here your code when it is not 
} 
0

您可以使用子方法。

String dummy = edittext.getText(); 

    if(dummy.substring(0,1).equalsIgnoreCase("a")){ 
    //your code goes here 

    }