0

I have a string, and I can detect if it has an # inside it.

    if(title.contains("#")){

        SpannableString WordtoSpan = new SpannableString(title);   

        int idx = title.indexOf("#");
        if (idx >= 0) {
            int wordEnd = title.indexOf(" ", idx);
            if (wordEnd < 0) {
                wordEnd = title.length();
            }
            WordtoSpan.setSpan(new ForegroundColorSpan(Color.RED),
                        idx,
                        wordEnd,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }           

        holder.txtTitle.setText(WordtoSpan);
    } else {
        holder.txtTitle.setText(title);
    }

So now, if the string has an # it will color it till the end of the word after it with red. This works perfectly. But the problem is, when a string has more than one # it will color only the first # with it word, not the next or the third etc ..

ex. Now: Notice it ill color only burger with red

I love chicken #burger , cuz they are #delicious.

I want: Notice bother burger and delicious are colored.

I love chicken #burger , cuz they are #delicious .

John Jared
  • 790
  • 3
  • 16
  • 40

2 Answers2

1

use title.split("#") to get a array of strings which contains #.

Something like:

String parts = title.split("#");
for(int i = 0; i<parts.length(); i++){
    //TODO: do something with the string part
    //parts[i], this is a part of the string.
}
Robin Dijkhof
  • 18,665
  • 11
  • 65
  • 116
1

You can use the Pattern to find and match words that contain hashtags in a given string.

String text = "I love chicken #burger, because they are #delicious!";

Pattern HASHTAG_PATTERN = Pattern.compile("#(\\w+|\\W+)");
Matcher mat = HASHTAG_PATTERN.matcher(text);

while (mat.find()) {
  String tag = mat.group(0);

  //String tag will contain the hashtag
  //do operations with the hashtag
}
cichy
  • 10,464
  • 4
  • 26
  • 36
Joel Fernandes
  • 4,776
  • 2
  • 26
  • 48