简体   繁体   中英

How to merge 2 while loops in JAVA to avoid repitition

I want to merge multiple while loops without necessary repeting myself. I have an array of strings like so:

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

My goal is to apply span effect when any of the array strings above are typed in editText. I could repeat the while loop and not use strings to begin with but for clean code, I want to put all strings in array and apply span effect to any of them if it's typed in edit text. Any idea how to achieve this?

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) {

        }
    });

You may nest the actual loop that searches and decorates a specific String if it is encountered by an outer loop that iterates on the set of String s to search and decorate.

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();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM