Counting Variations in Strings with Java

Day 22 | Programming Classes at TAP Academy 🧾 Count Variations in Strings ✨ 💥 Problem 1: Count Words in a String General Approach: words = spaces + 1; Looks correct but… 👉 What if multiple spaces exist? 👉 What if spaces appear at the start/end? logic breaks. ✅ Correct Insight A word starts when: current character = space next character ≠ space 💡 Final Code public static int countWords(String s) { int count = 0; for (int i = 0; i < s.length() - 1; i++) { if (s.charAt(i) == ' ' && s.charAt(i + 1) != ' ') { count++; } } // Handle starting space edge case if (s.charAt(0) == ' ') { return count; } else { return count + 1; } } 💥 Problem 2: Count Vowels in a String 💡 Logic A character is a vowel if: 👉 It matches a, e, i, o, u (both cases) ✅ Code int count = 0; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') { count++; } } 💥 Problem 3: Count Consonants Mostly say: 👉 “Not vowel = consonant” ❌ Wrong. Because: digits -> not vowels special characters -> not vowels But they are NOT consonants. ✅ Proper Approach Check if character is alphabet Then check: vowel -> vowel count else -> consonant 💡 Code public static int countConsonants(String s) { int cc = 0; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); // Check if alphabet if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { // Check if NOT vowel → consonant if (!(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')) { cc++; } } } return cc; } 💥 Final Boss Problem 👉 Count: Vowels Consonants Numbers Special characters 💡 Code public static void countCharacters(String s) { int vc = 0, cc = 0, nc = 0, sc = 0; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') { vc++; } else { cc++; } } else if (ch >= '0' && ch <= '9') { nc++; } else { sc++; } } } #Java #Programming #CodingInterview #DataStructures #ProblemSolving #LearnToCode #Developers #CodingJourney #TechSkills #Code #InterviewPreparation #CoreJava #Upskilling #Learning #DSA #Strings #Logics #Thinking #TAPAcademy

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories