You are given a string s
containing lowercase letters only. Write a program in Java to perform the following operations:
Your program should define and use the following methods:
public static String reverseString(String s)
public static String removeVowels(String s)
public static HashMap<Character, Integer> countOccurrences(String s)
Input:
String s = "hellothere"
Expected Output:
Reverse: erehtolleh
Remove Vowels: hllthr
Occurrences: {h=3, e=3, l=2, o=1, t=1, r=1}
Note: In this example, the word "hellothere" is reversed to "erehtolleh". The vowels (e, o, e, e) are removed to get "hllthr". The occurrences for each character are (h=3, e=3, l=2, o=1, t=1, r=1).
import java.util.HashMap;
public class StringManipulation {
public static void main(String[] args) {
String s = "hellothere";
System.out.println("Reverse: " + reverseString(s));
System.out.println("Remove Vowels: " + removeVowels(s));
System.out.println("Occurrences: " + countOccurrences(s));
}
public static String reverseString(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static String removeVowels(String s) {
return s.replaceAll("[aeiou]", "");
}
public static HashMap<Character, Integer> countOccurrences(String s) {
HashMap<Character, Integer> occurrences = new HashMap<>();
for (char c : s.toCharArray()) {
occurrences.put(c, occurrences.getOrDefault(c, 0) + 1);
}
return occurrences;
}
}
First, we define the StringManipulation
class with the main method. Inside the main method, the string to be manipulated is assigned to the s
variable.
The program then calls the three methods: reverseString
, removeVowels
, and countOccurrences
, passing the input string as a parameter to each method.
In the reverseString
method, we create a StringBuilder
object initialized with the input string. We use the reverse
method of StringBuilder
to reverse the string and return it as a string using the toString
method.
In the removeVowels
method, we use the replaceAll
method of the String
class with a regular expression [aeiou]
to remove all vowels from the string. The method returns the modified string without vowels.
In the countOccurrences
method, we create a HashMap<Character, Integer>
to store the counts of each character. We iterate through each character in the input string using a for-each loop. For each character, we use the getOrDefault
method of the HashMap
to get the current count of the character, and increment it by 1. Finally, we return the occurrences
HashMap with the counts for each character.