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
Counting Variations in Strings with Java
More Relevant Posts
-
Day 23 | Programming Classes at TAP Academy 🚨 Mastering String Problems: Logic Over Syntax You’re given a string: 👉 "he#l@lo123" Task? Remove only special characters. Sounds basic But this is where logic—not syntax—gets tested. 💥 The Real Trap Most of us write: if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') { result += ch; } Looks correct. But this removes numbers too ❌ 👉 Problem: remove only special characters 👉 Your code: removes everything except alphabets That’s not solving. That’s assuming. 🧠 Core Concept Every character falls into 3 buckets: Alphabet Numeric Special character So don’t try to detect special characters (it’s messy across Unicode ❌) 👉 Instead, keep what you know is valid if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) { result += ch; } 🔍 Underlying Logic Pattern Strings are immutable. So the real workflow is: ➡️ Traverse (for loop) ➡️ Extract (charAt(i)) ➡️ Validate (conditions) ➡️ Build new string String result = ""; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (Character.isLetterOrDigit(ch)) { result += ch; } } ⚡ Level Up: Rearranging the String New problem: 👉 Uppercase -> Lowercase -> Numbers (remove specials) Two approaches: Approach 1 (naive): 3 loops -> O(3n) Approach 2 (optimized): 1 loop + 3 strings -> O(n) String uc="", lc="", nc=""; for(char ch : s.toCharArray()){ if(ch >= 'A' && ch <= 'Z') uc += ch; else if(ch >= 'a' && ch <= 'z') lc += ch; else if(ch >= '0' && ch <= '9') nc += ch; } return uc + lc + nc; 👉 Same result. Better thinking. 💣 The Dangerous Bug (ASCII Trap) You try to sum numbers: sum += ch; Output? ❌ 155 instead of 11 Why? 👉 '2' = 50, '4' = 52, '5' = 53 👉 You added ASCII, not actual numbers 🔥 Fix: sum += (ch - '0'); 👉 Converts char -> actual digit ⚠️ Operator Precedence Trap This looks harmless: result += ch + 32; But gives ❌ "H32E32..." Why? 👉 String + char + int -> left to right evaluation 🔥 Fix: result += (char)(ch + 32); 🔄 Case Conversion Logic (No Inbuilt Methods) Key insight: 👉 'A' → 'a' difference = 32 So: Upper → Lower → +32 Lower → Upper → -32 if(ch >= 'A' && ch <= 'Z'){ result += (char)(ch + 32); }else{ result += ch; } 🔁 Swap Case Logic if(ch >= 'A' && ch <= 'Z'){ result += (char)(ch + 32); } else if(ch >= 'a' && ch <= 'z'){ result += (char)(ch - 32); } else{ result += ch; } 👉 Clean. No shortcuts. Pure logic. #Java #CodingInterview #ProblemSolving #Developers #LearnToCode #Programming #TechCareers #CodeSmart #CoreJava #Strings #Logics #Thinking #Coding #Upskilling #Problems #Syntax #DSA #TAPAcademy #Software #Development #Learning
To view or add a comment, sign in
-
-
Programmers Don’t Need to Know Much Math The most common anxiety I hear about learning to program is the notion that it requires a lot of math. Actually, most programming doesn't require math beyond basic arithmetic. In fact, being good at programming isn't that different from being good at solving Sudoku puzzles. To solve a Sudoku puzzle, the numbers from one to nine are placed in a grid with a field for each row, so each row and each 3x3 interior square of the full 9x9 game, some numbers are provided to give you a start, and you find a solution by making deductions based on these numbers. What this really means is that programming is more about thinking than calculating. Just like Sudoku, you are not doing heavy mathematics. You are looking for patterns, understanding rules, and making logical decisions step by step. You observe what is already given, you test possibilities, and you adjust when something does not work. That is exactly how coding works, too. When you write code, you are not sitting there solving complex equations. You are breaking problems into smaller parts, following instructions, and building solutions one step at a time. It is more about logic, patience, and practice than advanced math skills. So, if you have been holding back because you think you are not “good at math,” you might be worrying about the wrong thing. If you can think through problems, stay curious, and keep trying even when something does not work at first, you already have what it takes to start programming.
To view or add a comment, sign in
-
-
🚀 Understanding OOP Concepts in Simple Words Object-Oriented Programming (OOP) is one of the most important concepts every ICT student should learn but many beginners find it confusing at first. So I decided to break it down in a simple and practical way 👇 💡 In OOP, we think about code like real-world objects: A Car has properties like color and model, and actions like drive() A Dog has properties like breed and age, and actions like bark() A Person has properties like name and email, and actions like greet() 📌 OOP is mainly built on four key concepts: 🔹 Encapsulation – Keeping data and methods together 🔹 Inheritance – Reusing code from existing classes 🔹 Polymorphism – One action, different behaviors 🔹 Abstraction – Hiding unnecessary details 🎯 Why is OOP important? Because it helps us write clean, reusable, and scalable code—just like how real-world systems work. As someone passionate about becoming an IT lecturer, I always try to explain complex concepts in a way that students can easily understand. 📚 Teaching is not just about knowledge, it’s about making others understand. Let me know in the comments what topic should I explain next? 👇 #OOP #Programming #ICT #SoftwareEngineering #LearnWithJanu #CodingForBeginners #TechEducation #FutureLecturer #ITStudents #WebDevelopment
To view or add a comment, sign in
-
-
🚀 Learning OOP: Inheritance & Its Types Today, I explored one of the most powerful concepts in Object-Oriented Programming — Inheritance. 👉 What is Inheritance? Inheritance allows a class (child class) to acquire properties and methods from another class (parent class). It helps in code reusability, scalability, and cleaner structure. 🔹 Types of Inheritance I learned: 1. Single Inheritance One child class inherits from one parent class. 2. Multiple Inheritance One child class inherits from multiple parent classes. 3. Multilevel Inheritance A chain of inheritance (grandparent → parent → child). 4. Hierarchical Inheritance Multiple child classes inherit from a single parent class. 💡 Key Takeaways: - Reduces code duplication - Makes programs more modular - Improves maintainability 📌 Understanding inheritance is a big step toward mastering OOP and writing efficient code. #Python #OOP #Inheritance #CodingJourney #Programming #Learning
To view or add a comment, sign in
-
-
🚀 New Blog: How Short Videos Can Enhance Programming Skills Short-form videos like Reels and YouTube Shorts are not just for entertainment-they are becoming powerful tools for learning. 🔗 Read here: https://lnkd.in/g7Z9JtAC #Programming #Python #Learning #CodingSkills #YouTubeShorts #Reels #Microlearning #TechEducation SR University #SRUniversity #SRU
To view or add a comment, sign in
-
I’ve started writing to improve how I understand and explain concepts. My first blog focuses on a fundamental topic in programming—recursion vs iteration—and how they represent two different ways of thinking while solving problems. This is just the beginning. I’ll be writing on a mix of technical topics and general ideas going forward. Read here: https://lnkd.in/gw98ph77 #Programming #Learning #Algorithms #StudentJourney
To view or add a comment, sign in
-
Understanding Variables in Programming: The Mental Model Beginners Miss Why beginners struggle with variables isn’t syntax — it’s misunderstanding what variables actually represent inside a running program....
Understanding Variables in Programming: The Mental Model Beginners Miss https://thetechthriller.buzz To view or add a comment, sign in
-
*✅ Object-Oriented Programming (OOP) - Classes and Objects* 🚀 part 1. *What is Object-Oriented Programming (OOP)?* OOP = organizing code using objects and classes. Real-world idea: - Car → object - Student → object - Bank account → object Each object has: - Data (attributes) - Actions (methods) *What is a Class?* Class = blueprint/template to create objects. Example: Class = Student design, Object = actual student *Create a Class* class Student: pass Class created. No data yet. *Create an Object* s1 = Student() print(s1) Object = instance of class. *Attributes (Variables inside class)* class Student: name = "Mayur" age = 26 s1 = Student() print(s1.name) print(s1.age) But this is not practical. We use constructor. *Constructor init() ⭐* Runs automatically when object is created. class Student: def __init__(self, name, age): self.name = name self.age = age s1 = Student("Mayur", 26) s2 = Student("Amit", 22) print(s1.name) print(s2.name) Key idea: - `self` refers to current object - Stores object data *Methods (Functions inside class)* class Student: def __init__(self, name): self.name = name def greet(self): print("Hello, I am", self.name) s1 = Student("Priyansh") s1.greet() *Real Example: Bank Account* class BankAccount: def __init__(self, balance): self.balance = balance def deposit(self, amount): self.balance += amount def show_balance(self): print("Balance:", self.balance) acc = BankAccount(1000) acc.deposit(500) acc.show_balance() *Key Concepts You Must Remember* - Class → blueprint - Object → instance - `__init__` → constructor - `self` → current object - Methods → functions inside class 💡#Education #Teaching #Learning #SkillDevelopment #CareerGrowth
To view or add a comment, sign in
-
Programming used to be free "A middle schooler can learn Python on a family iPad. They can’t learn vibecoding" https://lnkd.in/d7xbmGnh #vibecoding #programming #llm
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development