Skip to content
This repository has been archived by the owner on Jan 15, 2023. It is now read-only.

adding a java program to check occurance of char in string #678

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions Java/OccurenceOfCharInString.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Java program to count frequencies of
// characters in string using Hashmap

class OccurenceOfCharInString {
static void characterCount(String inputString)
{
// Creating a HashMap containing char
// as a key and occurrences as a value
HashMap<Character, Integer> charCountMap
= new HashMap<Character, Integer>();

// Converting given string to char array

char[] strArray = inputString.toCharArray();

// checking each char of strArray
for (char c : strArray) {
if (charCountMap.containsKey(c)) {

// If char is present in charCountMap,
// incrementing it's count by 1
charCountMap.put(c, charCountMap.get(c) + 1);
}
else {

// If char is not present in charCountMap,
// putting this char to charCountMap with 1 as it's value
charCountMap.put(c, 1);
}
}

// Printing the charCountMap
for (Map.Entry entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}

// Driver Code
public static void main(String[] args)
{
String str = "Ajit";
characterCount(str);
}
}