Adrian
Adrian

Reputation: 15

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

Upvotes: 0

Views: 453

Answers (2)

jk47
jk47

Reputation: 765

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 ":"

Upvotes: 0

Duncan Jones
Duncan Jones

Reputation: 69339

This should work:

int length = groupMessage.indexOf(":") - groupMessage.indexOf(">") - 1;

It counts every character (including spaces) between the > and the :.

Upvotes: 1

Related Questions