Java Programs

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

Program 44: Write a Java program to remove consecutive duplicates in a string.

ConsecutiveDuplicates.java

import java.util.Scanner;

public class ConsecutiveDuplicates
{
	//Method to remove consecutive duplicates in a string.
	public static String removeConsecutiveDuplicates(String input)
	{
	    String str= "";
        str+=input.charAt(0);

		for(int i=1,j=0; i < input.length();i++)
        {
            if(input.charAt(i)!=str.charAt(j))
            {
                j++;
                str+=input.charAt(i);
            }else
            {
                continue;
            }
        }
	    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.next();

		System.out.println("String after removal of consecutive duplicates");
		System.out.println(ConsecutiveDuplicates.removeConsecutiveDuplicates(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.