Counting Characters in a String using Java

Write a program that coverts input like "aaaaabbccc" to output: a5b2c3

Using functional programming the solution to this problem is trivial. See for example the solution in Groovy:


input = "aaaaabbccc"

println input.toList().countBy{it}.collect{it.key + it.value}.join()

However, the solution using procedural programming is not as straightforward especially if you don't want to use utility classes like List and maps or dictionaries. Look for example at the the following solution in Java.



package realcodeexamples;

/**
 *
 * @author Trevor Sinkala
 */
public class RealCodeExamples {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println(countChars("aaaaaaaaabbcc"));
    }

    public static String countChars(String input) {
        String[] arr = new String[input.length()];
        for (int i = 0; i < input.length(); i++) {
            arr[i] = input.substring(i, i + 1);
        }
        String toReturn = "";
        for (int i = 0; i < arr.length; i++) {
            String character = arr[i];
            if(toReturn.indexOf(character) >= 0){
                continue;
            }
            int count = 0;
            for (int j = 0; j < arr.length; j++) {
                String string1 = arr[j];
                if(character.equals(string1)){
                    count++;
                }                
            }
            toReturn += character+count;
            
        }
        return toReturn;
    }

}



In this post we shall go through the steps to come up with such a solution...


Comments

Post a Comment

Popular posts from this blog

Creating a Simple "9 Lights Off" game in html

Ba Be Bi Bo Bu