Count consecutive repeating characters Program in java

Question:

Write a program to count the consecutive repeating characters.

Sample Input1:

aaabbcbbbb

Sample Output1:

a3b2c1b4

Sample Input2:

aaaabbcbbbb

Sample Output2:

a4b2c1b4

Sample Input3:

ascbnt

Sample Output2:

ascbnt

CODE:

import java.util.Scanner;
public class Main{
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.next();
        char[] char_arr = input.toCharArray();
        int count, i = 0;
        boolean cons = false;
        while(i <= char_arr.length - 1){
            count = 1;
            System.out.print(char_arr[i]);
            if(i == char_arr.length - 1)
                break;
            while(char_arr[i] == char_arr[i+1]){
                count++;
                cons = true;
                i++;
                if(i == char_arr.length - 1)
                    break;
            }
            i++;
            if(cons == true)
                System.out.print(count);
        }
    }
}
Next:
  1. Zig zag Array
  2. Pass and Fail Count
  3. Search a Course
  4. Average and Grade Calculation

Leave a Comment

Scroll to Top