We would like to know how to count the number of occurences of characters in a string.
import java.io.IOException; //from w w w . j av a 2s . com public class Main { public static void main(String[] args) throws IOException { String input = "this is a test"; StringBuilder result = new StringBuilder(); char currentCharacter; int count; for (int i = 0; i < input.length(); i++) { currentCharacter = input.charAt(i); count = 1; while (i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) { count++; i++; } result.append(currentCharacter); result.append(count); } System.out.println("" + result); } }