如何在Java中逐字比较两个字符串

时间:2019-07-28 05:07:18

标签: java android

我的代码:

String[] EtChArray = etValue.split("");
String[] VtChArray = fullStory.split("");

if (EtChArray[i].isEmpty()) {
   i++;
} else {
   if (EtChArray[i].equals(VtChArray[i])) {
       tview1.setText(EtChArray[i]);
       tview1.setTextColor(Color.GREEN);
       i++;
   } else {
       tview1.setText(EtChArray[i]);
       tview1.setTextColor(Color.RED);
       i++;

   }
}

我想在android studio(java)中将“编辑文本”与“视图文本”进行比较。我想在编辑文本框中输入文本,并将其与逐个字符的viewtext(预定义文本)实时进行比较,但是在组合空格时遇到问题。

2 个答案:

答案 0 :(得分:0)

    String s1 = "Hello world I am showkat";
    String s2 = "Hello world I was busy";

    String s1_words[] = s1.split("\\s");
    String s2_words[] = s2.split("\\s");

    int num_words = s1_words.length;

    if (num_words == s2_words.length) {
        for (int i = 0; i < num_words; i++) {
            System.out.print("word " + (i+1) + ": " + s1_words[i].equals(s2_words[i]) + "\n");
        }
    }

输出:

word 1: true

word 2: true

word 3: true

word 4: false

word 5: false

答案 1 :(得分:0)

    // Text View for Comparison
    final TextView tvText = (TextView) findViewById(R.id.textView);
    // Edit text View where you will type text
    final EditText tvEdit = (EditText) findViewById(R.id.editText);

    // Listener for checking change in text
    tvEdit.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void afterTextChanged(Editable mEdit)
        {
            if(mEdit.length() > 0){
                // Equals Ignore case if you dont want to check on the basis of case
                // This will check whether the typed string and your saved string upto that point match or not
                if(mEdit.toString().equalsIgnoreCase(tvText.getText().toString().substring(0,mEdit.length()))){
                    tvEdit.setTextColor(Color.GREEN);
                }else{
                    tvEdit.setTextColor(Color.RED);
                }
            }
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
        public void onTextChanged(CharSequence s, int start, int before, int count){}
    });
}