【问题标题】:Android: How to check String inside of EditText?Android:如何检查 EditText 中的字符串?
【发布时间】:2013-05-30 07:19:24
【问题描述】:

示例:我有一个 EditText 和 1 个按钮(onclick:示例)。我想检查在 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
}     

【问题讨论】:

标签: android if-statement


【解决方案1】:

使用startsWith()

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

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

【讨论】:

  • 谢谢,所有答案都有效。但这对我来说是最好的方式
【解决方案2】:
String arr[] = edittext.getText().toString().split(" ", 2);
String firstWord = arr[0];

【讨论】:

    【解决方案3】:

    试试这个对你有帮助

             String s=edittext.getText().toString().trim().charAt(0)+""
    
             if(s.equalsIgnoreCase("a")){
    
           give condition
               }
    

    【讨论】:

      【解决方案4】:
      String s = edittext.getText().toString();
      
      if (s.substring(0, s.indexOf(" ")).equalsIgnoreCase("a")) {
          // do stuff
      }
      

      【讨论】:

        【解决方案5】:
        if(edittext.getText().toString().split(" ")[0].equals("YOUR_STRING")) {
        //DO THE TASK
        }
        

        使用 null/empty check 你可以

        if (! TextUtils.isEmpty(editText.getText())) {
                    if ("LOOKING_STRING".equals(editText.getText().toString().split(" ")[0])) {
                        //DO THE TASK HERE
                    }
                }
        

        【讨论】:

          【解决方案6】:

          您还可以根据自己的情况使用更快的方法,如下所示:

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

          【讨论】:

            【解决方案7】:

            您可以使用子字符串方法。

                String dummy = edittext.getText();
            
                if(dummy.substring(0,1).equalsIgnoreCase("a")){
                //your code goes here
            
                }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-03-14
              • 1970-01-01
              • 1970-01-01
              • 2013-10-28
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多