Find Index of Character in String with Java Code Examples

Day 25 | Programming Classes at TAP Academy Strings Subsequences ✨ 🔍 Problem 1: Find the Index of a Character in a String Given a string S and a character K, find the index of K. 💡 Core logic: Traverse the string Compare each character using == Return index immediately when found If not found -> return -1 👉 Sounds basic… but execution exposed gaps. ⚠️ Big Reality Check The logic is literally the same as “index of element in array” — just applied to strings. 🧠 Hidden Trap: Taking Character Input in Java Most common mistake: Trying scanner.nextChar() ❌ (doesn’t exist) ✔️ Correct way: Take input as string Extract first character using .charAt(0) This tiny detail broke a lot of code. 🔁 Problem 2: Last Index of Character Same logic. Just reverse traversal. Start from length - 1 Move backwards Return first match Simple twist. Same foundation. 🔗 Problem 3: Subsequence Check Now things got interesting. 👉 Given two strings S and T, check if T is a subsequence of S. Meaning: All characters of T must appear in S Order must be maintained They don’t need to be continuous Example: S = "hereiamstackerrank" T = "hackerrank" → ✅ YES 💡 Approach Use two pointers: i -> for string S j -> for string T Logic: If characters match -> move both i++, j++ If not -> move only i++ Continue until end Final check: If j == T.length() → YES Else → NO 🧩 Bonus Concept: Loop Understanding Quick reminder that hit hard: while loop -> runs only if condition is true do-while loop -> runs at least once no matter what Understanding this difference = avoiding silent logical bugs. #Programming #Java #DSA #LearningJourney #CodingLife #ProblemSolving #TechGrowth #Software #Development #TAPAcademy #Upskilling #Logics #Strings #DSA #Coding #Problems #Logics #Syntax #CoreJava #Loops #Subsequence #Index #Learning

  • graphical user interface

To view or add a comment, sign in

Explore content categories