Search code examples
javaandroidstringcountwords

Counting characters in android


I need to count words. Starts from the character " > " to " : "

for example: I have this line: > User says: Hi people

I wonder how I can count the total of selection which start in ">" and finish ":"

Actually, my code in Java are:

String groupMessage = new String("> User says : Hi people");
String search = new String(">");


TextView groupMessageBox = (TextView) this
        .findViewById(R.id.groupMessageBox);

Spannable WordtoSpan = new SpannableString(groupMessage);

int length = search.length();
String input = WordtoSpan.toString();
int startIndex = input.indexOf(search);
while(startIndex > length)
{
    WordtoSpan.setSpan(new ForegroundColorSpan(Color.rgb(140, 117, 189)), startIndex, startIndex + length,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    WordtoSpan.setSpan(new StyleSpan(Typeface.BOLD), startIndex, startIndex + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    startIndex = input.indexOf(search, startIndex + length);
}
groupMessageBox.setText(WordtoSpan);

Someone can help me? Greetings


Solution

  • int start = groupMessage.indexOf(">") + 1;
    int end = groupMessage.indexOf(":") - 1;
    int numWords = groupMessage.substring(start, end).split("\\s+").length;
    

    This code assumes that you only care about the first time ">" and ":" come up, and that there is always a space after the ">" and before the ":"