gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 20:16:46 25 4
gpt4 key购买 nike

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

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

我的目标是在 editText 中键入上面的任何数组字符串时应用跨度效果。我可以重复 while 循环,并且不使用字符串作为开头,但为了干净的代码,我想将所有字符串放入数组中,并在编辑文本中输入字符串时对其中任何字符串应用跨度效果。知道如何实现这一目标吗?

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

}
});

最佳答案

如果在 String 集合上进行迭代以搜索和装饰的外部循环遇到该实际循环,则可以嵌套搜索和装饰特定 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();
}
}

关于java - 如何在JAVA中合并2个while循环以避免重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45662999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com