如何在JAVA中合并2个while循环以避免重复

时间:2017-08-13 17:24:42

标签: java android

我想合并多个while循环而不必重复自己。我有一个像这样的字符串数组:

String[] myStrings = { "Home", "Two", "Three" };

我的目标是在editText中输入任何上面的数组字符串时应用span效果。我可以重复while循环并且不使用字符串开头但是对于干净的代码,我想将所有字符串放在数组中并且如果在编辑文本中键入,则将span效果应用于其中任何字符串。知道怎么做到这一点?

public void onTextChanged(CharSequence s, int start, int before, int count) {
            String str="home";
            Spannable spannable =textA.getText();
            if(s.length() != 0) {
                textA.setTextColor(Color.parseColor("#0000FF"));
                ForegroundColorSpan fcs = new ForegroundColorSpan( Color.GREEN);
                String s1 = s.toString();
                int in=0; // start searching from 0 index

// keeps on searching unless there is no more function string found
                while ((in = s1.indexOf(str,in)) >= 0) {
                    spannable.setSpan(
                            fcs,
                            in,
                            in + str.length(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    // update the index for next search with length
                    in += str.length();
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

1 个答案:

答案 0 :(得分:3)

如果外部循环遇到String s集合进行搜索和装饰,您可以嵌套搜索并装饰特定String的实际循环。

for (String stringToSearch : myStrings){
   int in = 0; // start searching from 0 index for each new word to match
   while ((in = s1.indexOf(stringToSearch,in)) >= 0) {
    spannable.setSpan(
            fcs,
            in,
            in + stringToSearch.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    // update the index for next search with length
    in += stringToSearch.length();
  }
}