WAP to Count Consecutive Characters Count in a String

Count Consecutive Characters Count in a String: This Java program aims to generate an output string based on a given input string. The input string is defined as “AAAADDDCCCA”. The desired output is a string where the count of consecutive occurrences of that character follows each character.

For example, given the input string “AAAADDDCCCA”, the expected output is “A4D3C3A1”.

Count Consecutive Characters Count in a String

package com.softwaretestingo.interviewprograms;
public class InterviewPrograms11 
{
	/*
	 * Input string =AAAADDDCCCA 
	 * Output= A4D3C3A1
	 */
	public static void main(String[] args) 
	{
		String s = "AAAADDDCCCA";
		int count = 1;
		String re = "" ;
		for (int i = 0 ; i <=s.length()-1; i++ )
		{
			if ( i == s.length()-1 & count == 1 )
			{
				re = re + s.charAt(i)+count;
				break ;
			}
			if ( s.charAt(i) == s.charAt(i+1))
			{
				count++;
			}
			else
			{
				re = re + s.charAt ( i ) + count ;
				count = 1 ;
			}

		}
		System.out.println ( re ) ;
	}
}

Output:

A4D3C3A1

Explanation:

Initialize the input string: The input string is assigned to the variable s.

String s = "AAAADDDCCCA";

Initialize necessary variables: The variable count is set to 1 to count the consecutive occurrences of each character. The variable re will store the generated output string.

int count = 1;
String re = "";

Process the input string and generate the output: The program uses a for loop to iterate through each character of the input string s. It compares each character with the next character. If they are the same, the count variable is incremented. If they are different, the current character and its count are appended to the re string. The count is then reset to 1 for the next character.

for (int i = 0; i <= s.length() - 1; i++) {
    if (i == s.length() - 1 & count == 1) {
        re = re + s.charAt(i) + count;
        break;
    }
    if (s.charAt(i) == s.charAt(i + 1)) {
        count++;
    } else {
        re = re + s.charAt(i) + count;
        count = 1;
    }
}

Print the output string: The generated output string re is printed.

System.out.println(re);

In summary, this program takes an input string, counts the consecutive occurrences of each character, and generates an output string by concatenating each character with its respective count. The program demonstrates the usage of loops, string manipulation, and conditional statements in Java.

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment