Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 46: Write a Java program to do basic string compression. For a character which is consecutively repeated more than once, replace consecutive duplicate occurrences with the count of repetitions.

CompressString.java

import java.util.Scanner;

public class CompressString
{
	//Method to compress the string.
	public static String compress(String inputString)
	{
	    String str="";
        int count=1;
        str+=inputString.charAt(0);
        for(int i=1,j=0; i<=inputString.length(); i++)
        {
            if(i==inputString.length())
            {
                if(count!=1)
                {
                    str+=String.valueOf(count); //valueOf method is used to convert integer to string.
                }
            }
            else if(str.charAt(j)==inputString.charAt(i))
            {
                count++;
            }
            else 
            {
                if(count==1)
                {
                    j++;
                    str+=inputString.charAt(i);
                }else
                {
                    j+=2;
                    str+=String.valueOf(count)+inputString.charAt(i);
                     count=1;
                }
            }
        }
        return str;
	}

	//Main method
	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the string");
		String input = s.nextLine();

		System.out.println("Compressed string");
		System.out.println(CompressString.compress(input));
	}
}


If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.