• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

  • Home
  • Test Case Examples
  • Interview Questions
  • Interview Questions Asked
  • Java
  • Selenium
  • Manual Testing
  • SQL Tutorial For Beginners
  • Difference
  • Tools
  • Contact Us
  • Search
SoftwareTestingo Â» Java Â» Java Programs Â» WAP to Count Occurrence of Characters in a String

WAP to Count Occurrence of Characters in a String

Last Updated on: July 27, 2023 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • Count Occurrence of Characters in a String

Count Occurrence of Characters in a String: This Java program takes an input string “AAAABBCCCDDDDEEEG” and generates an output string “A4B2C3D4E3G1”. The program compresses the input string by representing each character and the number of occurrences of that character consecutively.

Count Occurrence of Characters in a String

package com.softwaretestingo.interviewprograms;
import java.util.ArrayList;
public class InterviewPrograms19 
{
	/*
	 * Input string "AAAABBCCCDDDDEEEG" 
	 * Output string "A4B2C3D4E3G1"
	 */ 
	public static void main(String[] args) 
	{
		String s ="AAAABBCCCDDDDEEEG";
		ArrayList<Character> list = new ArrayList<>();
		for(int i=0;i<s.length();i++)
		{
			int count=1;
			if(!list.contains(s.charAt(i)))
			{
				list.add(s.charAt(i));
				for(int j=i+1;j<s.length();j++)
				{
					if(s.charAt(i)==s.charAt(j))
					{
						count++;
					}
				}
				System.out.print(s.charAt(i)+""+count);
			}
		}
	}
}

Output

A4B2C3D4E3G1

Let’s break down the program step by step for Java beginners:

  • Package and Import Statements:
    • The program is part of the package com.softwaretestingo.interviewprograms.
    • It imports the ArrayList class from the java.util package to use dynamic arrays.
  • Class and main() Method:
    • The program defines a class called InterviewPrograms19.
    • It contains a main method, the entry point of the program, which will be executed first.
  • Input String:
    • String s = “AAAABBCCCDDDDEEEG”;: This line declares and initializes the input string s with the value “AAAABBCCCDDDDEEEG”.
  • ArrayList Initialization:
    • ArrayList<Character> list = new ArrayList<>();: An ArrayList called list is created to store unique characters encountered in the input string.
  • Looping through the Input String:
    • for(int i=0; i<s.length(); i++) { … }: The program uses a for loop to iterate over each character of the input string.
  • Character Counting:
    • int count = 1;: A variable count is initialized to 1 to count the occurrences of the current character.
  • Checking for Unique Characters:
    • if (!list.contains(s.charAt(i))) { … }: This if condition checks if the current character is not present in the list, which means it’s a new character.
  • Adding Unique Characters to the List and Counting Occurrences:
    • list.add(s.charAt(i));: If the character is unique, it’s added to the list.
    • The program then uses another for loop (nested within the first loop) to find the number of occurrences of this unique character by comparing it with the remaining characters in the string.
  • Printing the Compressed Output:
    • System.out.print(s.charAt(i) + “” + count);: After counting the occurrences of the current unique character, it’s printed along with its count.
  • Output:
    • The output of the program will be “A4B2C3D4E3G1”, which represents the compressed version of the input string “AAAABBCCCDDDDEEEG”.

In summary, this Java program takes an input string, compresses it by counting consecutive occurrences of each character, and then prints the compressed version of the string.

Alternative 1:

This Java program achieves the same goal as the previous one, which is to compress an input string “AAAABBCCCDDDDEEEG” into an output string “A4B2C3D4E3G1”. However, it uses a different approach to achieve this compression.

package com.softwaretestingo.interviewprograms;
import java.util.HashMap;
import java.util.Map;
public class InterviewPrograms19_1 
{
	/*
	 * Input string "AAAABBCCCDDDDEEEG" 
	 * Output string "A4B2C3D4E3G1"
	 */ 
	public static void main(String[] args) 
	{
		String s = "AAAABBCCCDDDDEEEG";
		String[] sArray = s.split("");
		Map<String, Integer> map = new HashMap<>();
		for(String temp : sArray) {
			if(map.containsKey(temp)) {
				map.put(temp, map.get(temp)+1);
			}
			else {
				map.put(temp, 1);
			}
		}
		System.out.println(map.toString().replaceAll("\\W",""));
	}
}

Output

A4B2C3D4E3G1

Let’s break down the program section by section for Java beginners:

  1. Package and Import Statements:
    • The program is part of the package com.softwaretestingo.interviewprograms.
    • It imports the HashMap and Map classes from the java.util package to work with key-value pairs.
  2. Class and main() Method:
    • The program defines a class called InterviewPrograms19_1.
    • It contains a main method, the entry point of the program, which will be executed first.
  3. Input String:
    • String s = “AAAABBCCCDDDDEEEG”;: This line declares and initializes the input string s with the value “AAAABBCCCDDDDEEEG”.
  4. Splitting the Input String:
    • String[] sArray = s.split(“”);: The input string s is split into an array of individual characters using the split(“”) method.
  5. Creating a HashMap:
    • Map<String, Integer> map = new HashMap<>();: A HashMap called map is created to store characters as keys and their occurrences as values.
  6. Looping through the Input Characters:
    • for(String temp : sArray) { … }: The program uses an enhanced for loop to iterate over each character in the sArray.
  7. Counting Character Occurrences:
    • if(map.containsKey(temp)) { … }: It checks if the current character (temp) is already present in the map.
  8. Updating the HashMap:
    • If the character is already in the map, its corresponding value (occurrence count) is incremented by one.
    • If the character is not present in the map, it’s added to the map with an initial occurrence count of 1.
  9. Printing the Compressed Output:
    • System.out.println(map.toString().replaceAll(“\\W”,””));: After counting occurrences of all characters, the program prints the compressed output.
    • map.toString() converts the map to a string representation (e.g., “{A=4, B=2, C=3, D=4, E=3, G=1}”).
    • .replaceAll(“\\W”,””) removes all non-word characters (non-alphanumeric characters) from the string, resulting in the desired compressed output “A4B2C3D4E3G1”.

In summary, this Java program compresses the input string by counting the occurrences of each character using a HashMap, and then it prints the compressed output in the format “A4B2C3D4E3G1”.

Alternative 2:

This Java program also achieves the goal of compressing the input string “AAAABBCCCDDDDEEEG” into the output string “A4B2C3D4E3G1”. It uses a HashMap to count the occurrences of each character in the input string and then prints the compressed output.

package com.softwaretestingo.interviewprograms;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class InterviewPrograms19_2 
{
	/*
	 * Input string "AAAABBCCCDDDDEEEG" 
	 * Output string "A4B2C3D4E3G1"
	 */ 
	public static void main (String [] args)
	{
		String str = "AAAABBCCCDDDDEEEG";
		occurences (str);
	}
	public static void occurences(String str)
	{
		int count = 0 ;
		Map <Character, Integer> hs=new HashMap <Character ,Integer>();
		for ( int i = 0 ; i<str.length(); i++) 
		{
			if ( hs.containsKey(str.charAt(i))) 
			{
				count =hs.get(str.charAt(i));
				count = count+1;
				hs.put(str.charAt(i),count);
			} 
			else 
			{
				hs.put(str.charAt(i), 1);
			}
		}
		Set<Map.Entry <Character, Integer>> s = hs.entrySet();
		for (Entry<Character,Integer> s1 : s ) 
		{
			System.out.print (s1.getKey()+ ""+s1.getValue());  
		}            
	}
}

Output

A4B2C3D4E3G1

Let’s break down the program section by section for Java beginners:

  1. Package and Import Statements:
    • The program is part of the package com.softwaretestingo.interviewprograms.
    • It imports several classes from the java.util package, including HashMap, Map, Entry, and Set, which are used for handling key-value pairs.
  2. Class and main() Method:
    • The program defines a class called InterviewPrograms19_2.
    • It contains a main method, the entry point of the program, which will be executed first.
  3. Input String:
    • String str = “AAAABBCCCDDDDEEEG”;: This line declares and initializes the input string str with the value “AAAABBCCCDDDDEEEG”.
  4. Calling the occurences() Method:
    • occurences(str);: The program calls the occurences() method, passing the input string str to it for processing.
  5. occurences() Method:
    • public static void occurences(String str) { … }: This method takes a string as input and is responsible for counting the occurrences of each character.
  6. Initializing the HashMap:
    • Map<Character, Integer> hs = new HashMap<Character, Integer>();: A HashMap called hs is created to store characters as keys and their occurrences as values.
  7. Looping through the Input Characters:
    • The program uses a for loop to iterate over each character in the input string str.
  8. Counting Character Occurrences using HashMap:
    • If the character is already present in the hs HashMap, the program retrieves its current count, increments it by one, and puts the updated count back into the hs.
    • If the character is not present in the hs HashMap, it is added to the hs with an initial count of 1.
  9. Printing the Compressed Output:
    • Set<Map.Entry<Character, Integer>> s = hs.entrySet();: The program gets the entry set of the hs HashMap to iterate over its key-value pairs.
  10. Looping through HashMap Entries and Printing:
    • The program uses an enhanced for loop to iterate over each entry (s1) in the entry set s.
    • It then prints the key (character) and value (occurrence count) of each entry, resulting in the compressed output format “A4B2C3D4E3G1”.

In summary, this Java program also compresses the input string by counting the occurrences of each character using a HashMap, and then it prints the compressed output in the format “A4B2C3D4E3G1”.

    WAP to Move Zeros Left By Maintaining the Order Of Digits
    WAP to Move Zeros Left By Maintaining the Order Of...
    WAP to Reverse String Without Affecting Digits Position
    WAP to Reverse String Without Affecting Digits Position
    Java Array Programs
    Java Array Programs
    WAP to Remove Characters That Appear More Than K Times
    WAP to Find Kth Smallest Element in an Array
    Kth Largest Element in an Array
    WAP to Find Kth Largest Element in an Array
    Reverse Words without Changing Order & Split
    WAP to Reverse Words without Changing Order & Split
    WAP to Count Consecutive Characters Count in a String
    WAP to Count Consecutive Characters Count in a String
    WAP For Removing White Spaces In A String
    WAP For Removing White Spaces In A String
    Swap Two Numbers In Java
    Swap Two Numbers In Java
    WAP For Sorting Characters Alphabetically Ignoring Case Sensitive
    WAP For Sorting Characters Alphabetically Ignoring Case Sensitive

    Filed Under: Java Programs

    Reader Interactions

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Categories

    Footer

    Java Tutorial for Beginners | Selenium Tutorial | Manual Testing Tutorial | SQL Tutorial For Beginners | GitHub Tutorial For Beginners | Maven Tutorial

    Copyright © 2023 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy ~ Testing Careers