Remove consecutive characters

Write a program to input a word from the user and remove the consecutive repeated characters by replacing the sequence of repeated characters by its single occurrence.
Example:
INPUT – Jaaavvvvvvvvaaaaaaaaaaa OUTPUT – Java
INPUT – Heeeiiiissggoiinggg OUTPUT – Heisgoing


import java.util.*;
class RemoveRepChar
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter any word: "); // Inputting the word
        String s = sc.nextLine();
        s = s + " "; // Adding a space at the end of the word
        int l=s.length(); // Finding the length of the word
        String ans=""; // Variable to store the final result
        char ch1,ch2;
        for(int i=0; i<l-1; i++)
        {
            ch1=s.charAt(i); // Extracting the first character
            ch2=s.charAt(i+1); // Extracting the next character

            /* Adding the first extracted character to the result 
               if the current and the next characters are different*/

            if(ch1!=ch2)
            {                   
            ans = ans + ch1;
            }
        }
        System.out.println("Word after removing repeated characters = "+ans); // Printing the result
    }
}

No comments:

Post a Comment

any problem in any program comment:-

Second largest number in java using ternary operator

 //Largest second number using ternary operator public class Main { public static void main(String[] args) { int a=5,b=6,c=7; int ...