Android获取最接近的字符或单词结尾
我使用Android获取最接近的字符或单词结尾,android,Android,我使用indexof()查找特定字符的长度,然后使用不同的颜色对其进行着色。我可以使用indexof()精确地从字符开始着色,这很好,但我不能以单词结尾 if(title.contains("x")){ SpannableString WordtoSpan = new SpannableString(title); WordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), title.indexOf("x"),
indexof()
查找特定字符的长度,然后使用不同的颜色对其进行着色。我可以使用indexof()
精确地从字符开始着色,这很好,但我不能以单词结尾
if(title.contains("x")){
SpannableString WordtoSpan = new SpannableString(title);
WordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), title.indexOf("x"), title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.txtTitle.setText(WordtoSpan);
} else {
holder.txtTitle.setText(title);
}
现在,如果它包含字符x
,它将从找到的第一个x
开始将其涂上红色。但是直到最后一根我不喜欢的绳子,它才会结束
我希望它以以以x
开头的单词结尾
例如现在:(粗体是红色atm)
我喜欢《x战警》和巧克力。
我想要的是:
我喜欢《x战警》和巧克力
我如何做到这一点?你必须找到单词的结尾,而不是简单地传递长度() 考虑一个更健壮的算法来查找单词分隔符(即包含制表符),在这个示例中,我只需查找第一个空格
String s = "I love x-man and chocolate.";
int idx = s.indexOf("x");
if (idx >= 0) {
int wordEnd = s.indexOf(" ", idx);
if (wordEnd < 0) {
wordEnd = s.length();
}
WordtoSpan.setSpan(new ForegroundColorSpan(Color.RED),
idx,
wordEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
String s=“我喜欢x战警和巧克力。”;
int idx=s.indexOf(“x”);
如果(idx>=0){
int-wordEnd=s.indexOf(“,idx);
if(wordEnd<0){
wordEnd=s.length();
}
WordtoSpan.setSpan(新的前地面颜色Span(颜色为红色),
idx,
wordEnd,
Spannable.SPAN_独占性SPAN_独占性);
}