Write a Java Program to count the number of words in a string using HashMap.
Answers
★·.·´¯`·.·★ ʜᴇʀᴇ ɪs ʏᴏᴜʀ ᴀɴsᴡᴇʀ ★·.·´¯`·.·★
This is a collection class program where we have used HashMap for storing the string.
First of all, we have declared our string variable called str. Then we have used split() function delimited by single space so that we can split multiple words in a string.
Thereafter, we have declared HashMap and iterated using for loop. Inside for loop, we have an if else statement
in which wherever at a particular position, the map contains a key, we set the counter at that position and add the object to the map.
Each time, the counter is incremented by 1. Else, the counter is set to 1.
Finally, we are printing the HashMap.
Note: The same program can be used to count the number of characters in a string. All you need to do is to remove one space (remove space delimited in split method) in String[] split = str.split(“”);
1
import java.util.HashMap;
2
3
public class FinalCountWords {
4
5
public static void main(String[] args) {
6
// TODO Auto-generated method stub
7
String str = "This this is is done by Saket Saket";
8
String[] split = str.split(" ");
9
HashMap<String,Integer> map = new HashMap<String,Integer>();
10
for (int i=0; i<split.length-1; i++) {
11
if (map.containsKey(split[i])) {
12
int count = map.get(split[i]);
13
map.put(split[i], count+1);
14
}
15
else {
16
map.put(split[i], 1);
17
}
18
}
19
System.out.println(map);
20
}
21
22
}
Output:
{Saket=1, by=1, this=1, This=1, is=2, done=1}
ᴇʜsᴀss ✿◕ ‿ ◕✿
Given a string, the task is to write a program in Java which prints the number of occurrences of each character in a string.
Examples:
Input: str = "GeeksForGeeks"
Output:
r 1
s 2
e 4
F 1
G 2
k 2
o 1
Input: str = "Ajit"
Output:
A 1
t 1
i 1
j 1
✌✌✌✌✌✌✌✌✌
☺☺☺☺☺☺☺
#misSpeAceE❤