Consecutive and Repeated Characters in a String

Write a program to input a string from the user and display all the consecutive and repeated characters in that string.

Example:
INPUT: understanding computer science
OUTPUT:
Consecutive characters: d e r s s t
Repeated characters: u n d e r s t i c

import java.io.*;
class Consecutive{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter the string: ");
        String s = br.readLine().toLowerCase();
        String repeated = "";
        String consecutive = "";
        for(int i = 0; i < s.length() - 1; i++){ 
            char ch1 = s.charAt(i); 
            char ch2 = s.charAt(i + 1); 
            if(ch1 + 1 == ch2) 
                consecutive += ch1 + " " + ch2 + " "; 
        } 
        System.out.println("Consecutive characters:\n" + consecutive); 
        while(s.length() > 0){
            char ch = s.charAt(0);
            int count = frequency(s, ch);
            if(!isPresent(repeated, ch) && count > 1)
                repeated += ch + " ";
            s = s.replace(Character.toString(ch), "");
        }
        System.out.println("Repeated characters:\n" + repeated);
    }
    public static boolean isPresent(String s, char ch){
        boolean status = false;
        for(int i = 0; i < s.length(); i++){
            if(ch == s.charAt(i)){
                status = true;
                break;
            }
        }
        return status;
    }
    public static int frequency(String s, char ch){
        int count = 0;
        for(int i = 0; i < s.length(); i++){
            if(ch == s.charAt(i)){
                count++;
            }
        }
        return count;
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.