Count the letter repetition in a string Given a String. we have to print out the letter repetition

Sample input "aaaabbaac"

Sample output "4a2b2a1c"

public void continousWords(String input) {
String sample= input +" ";
String[] sampleList  =   sample.split("");
String temp = sampleList[0];
String result="";
int placeHolder=0;
for(int i=0;i&lt;sampleList.length;i++){

    if(temp.equalsIgnoreCase(sampleList[i])) {
        placeHolder++;

    }
    else {
      result = result+placeHolder+temp;
      placeHolder =1;
      temp = sampleList[i];
    }

}
System.out.println(result);

}


Is there a better way to approach the problem
This method doesn't need any member of it's class, thus it can be declaced static.

You want to count the repetation of each letter, not the frequency in the string, don't you? At least, that's what I understood from your example result 4a2b2a1c where a is included twice. If you want the frequency 6a2b1c the algorithm would be different.

AN alternative approach to your proposal would be to convert the String in a char array and to analyze that.

public static void continousWords(String input) {
    char[] chars = input.toLowerCase().toCharArray();
    StringBuilder b = new StringBuilder();

    for (int i = 0, count; i &lt; chars.length; i += count) {
        count = 1;
        while (i + count &lt; chars.length &amp;&amp; chars[i] == chars[i + count])
            count++;
        b.append(count).append(chars[i]);
    }

    String result = b.toString();
    System.out.println(result);
}