Interview Prep with Java: Tackling Consonants and Character Frequency Problems
Tushar Kumar
Aspiring Software Engineer | Java, Spring Boot, React Enthusiast | Eager to Tackle Real-World Challenges | Ready to Deliver Innovative Solutions as a Fresh Talent | CDAC Certified
?? Interview Challenge: Tackling String Manipulation ??
In my recent interview, I was presented with two interesting string-related questions that made me think! ??
Question 1: ?? Find the consonants in a given string. The challenge was to quickly identify and filter out only the consonants from the string, ignoring vowels, spaces, and special characters.
import java.util.Scanner;
public class ConsonantsFromWord {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get input word from user
System.out.print("Enter a word: ");
String word = scanner.nextLine();
System.out.println("Consonants in the word are: ");
printConsonants(word);
scanner.close();
}
// Function to print consonants from a word
public static void printConsonants(String word) {
// Convert word to lowercase for easier comparison
word = word.toLowerCase();
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
// Check if the character is a consonant
if (ch >= 'a' && ch <= 'z' && !isVowel(ch)) {
System.out.print(ch + " ");
}
}
}
// Helper function to check if a character is a vowel
public static boolean isVowel(char ch) {
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}
}
领英推荐
Question 2:?? Find the frequency of each character in the string. Given the string "Tushar Kumar", I had to calculate the frequency of each character while ignoring spaces.
import java.util.HashMap;
import java.util.Map;
public class CharacterFrequency {
public static void main(String[] args) {
String str = "Tushar Kumar";
findCharFrequency(str);
}
public static void findCharFrequency(String str) {
Map<Character, Integer> frequencyMap = new HashMap<>();
for (char ch : str.replaceAll("\\s", "").toCharArray()) {
frequencyMap.put(ch, frequencyMap.getOrDefault(ch, 0) + 1);
}
System.out.println("Character Frequency: " + frequencyMap);
}
}
These types of problems are always a great way to sharpen your logical thinking and coding skills. If anyone has a cool approach to solving these, I’d love to hear your thoughts! ??
#coding #interviewprep #problemSolving #stringManipulation #developerlife #techiebyprofessionalism
AI Engineer | Looking For Jobs | JAVA | SQL | PYTHON | Eager to Tackle Real-World Challenges | Ready to Deliver Innovative Solution as a fresh Talent |
5 个月Very helpful