Remove Consecutive Characters from a String in Java

Write a program to input a word from the user and remove the consecutive repeated characters replacing sequence of repeated characters by its single occurrence.

Example 1:
INPUT: Jaaavvvvvvvvaaaaaaaaaaaaa
OUTPUT: Java

Example 2:
INPUT: Heeeeeeiiiiiisssssssggoiingggg
OUTPUT: Heisgoing

Program:

import java.io.*;
class Consecutive{
    public static void main(String args[])
    throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("Enter the string: ");
        String s = br.readLine();
        String t = new String();
        int len = s.length();
        for(int i = 0; i < len; i++){
            char ch = s.charAt(i);
            t += ch;
            while(i + 1 < len && s.charAt(i + 1) == ch)
                i++;
        }
        System.out.println(t);
    }
}

Leave a Reply

%d bloggers like this: