Wednesday, October 26, 2011

A simple compression program in java

package org.learn.compression;

public class Compression {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String toBeCompressed = "aaaaaabbbbbcccce4uiiiioookkkkkkkkkkkkkkkkkkkkkkkk";
        String compressed = compress(toBeCompressed);
       
        System.out.println("String to Compressed="+toBeCompressed + ", length="+toBeCompressed.length());
        System.out.println("Compressed String ="+compressed+ ", length="+compressed.length());
    }
   
    public static String compress(String str){
        String compressedStr="";
        String countChar="";
        int index=0;
        int strLength = str.length();
        while(true){
            char c = str.charAt(index);
            int count=1;
            int temp=index;
            while(true){
                countChar="";
                ++temp;
                if( temp<strLength && c == str.charAt(temp)){
                    count++;
                }else{
                    countChar = c + ""+count;
                    break;
                }
            }
            compressedStr = compressedStr + countChar;
            index+=count;
            if(index>=strLength)
                break;
        }
        return compressedStr;
    }

}

No comments:

Post a Comment