This collection of 30 C# string exercises is built to strengthen your grasp of string manipulation, covering everything from basic built-in methods to manual algorithms..
Each exercise includes a Practice Problem, Purpose, Hint, and a full Solution with Explanation, so you understand the reasoning behind every line of code.
Also, See: C# Exercises with 22 topic-wise sets and 620+ practice questions.
What You’ll Practice
- Fundamentals: String methods, immutability, and
StringBuilder. - Manipulation: Reversing, trimming, case conversion, and searching.
- Analysis: Palindrome checks, anagrams, character frequency, and word counting.
- Formatting: String interpolation and custom formatting patterns.
+ Table Of Contents (30 Exercises)
Table of contents
- Exercise 1: Length Calculator
- Exercise 2: Reverse a String
- Exercise 3: Character Separator
- Exercise 4: Vowel & Consonant Counter
- Exercise 5: Alphabet, Digit, and Special Character Counter
- Exercise 6: Case Converter
- Exercise 7: Word Counter
- Exercise 8: Sub-string Checker
- Exercise 9: String Trimmer
- Exercise 10: String Compactor (Manual Comparison)
- Exercise 11: Sentence Reverser
- Exercise 12: Character Frequency Counter
- Exercise 13: Most Frequent Character
- Exercise 14: Manual Substring Extractor
- Exercise 15: Alphabetical Sorter
- Exercise 16: Duplicate Remover
- Exercise 17: Title Case Converter
- Exercise 18: Palindrome Checker
- Exercise 19: Anagram Detector
- Exercise 20: String Padding Creator
- Exercise 21: Find All Substrings
- Exercise 22: Longest Common Prefix
- Exercise 23: First Non-Repeated Character
- Exercise 24: String to Integer (Manual Parse)
- Exercise 25: Run-Length Encoding (RLE)
- Exercise 26: Valid Parentheses
- Exercise 27: URL Encoder
- Exercise 28: String Rotation Checker
- Exercise 29: Caesar Cipher Implementation
- Exercise 30: Longest Substring Without Repeating Characters
Exercise 1: Length Calculator
Practice Problem: Write a program to find the length of a string without using the built-in .Length property.
Purpose: This exercise helps you practice using a loop to count elements manually, reinforcing how properties like .Length work internally by iterating through every character.
Given Input: text = "Programming"
Expected Output:
Calculating length of "Programming": Length = 11 Length calculation completed successfully.
▼ Hint
- Initialize a counter variable to 0.
- Use a
foreachloop to iterate through each character of the string. - Increment the counter once for every character encountered, then the counter holds the string’s length.
▼ Solution & Explanation
Explanation:
class LengthCalculator: Defines the class that holds the program’s entry point and counting logic.int length = 0: Initializes a counter to track the number of characters.foreach (char ch in text): Iterates through each character in the string without using.Length.length++: Increments the counter once for every character encountered.
Exercise 2: Reverse a String
Practice Problem: Accept a string and print it in reverse order.
Purpose: This exercise helps you practice the two-pointer technique, swapping characters from opposite ends of an array to reverse it in place.
Given Input: text = "hello"
Expected Output:
Reversing the string "hello": Reversed String: olleh String reversal completed successfully.
▼ Hint
- Convert the string into a character array using
ToCharArray(). - Use two index variables, one starting at the beginning and one at the end.
- Swap the characters at both positions and move the indices toward the middle until they meet.
▼ Solution & Explanation
Explanation:
class StringReverser: Defines the class that holds the program’s entry point and reversal logic.char[] characters = text.ToCharArray(): Converts the string into a character array so individual characters can be swapped.int start = 0; int end = characters.Length - 1;: Sets up two pointers at opposite ends of the array.while (start < end): Continues swapping until the two pointers meet or cross in the middle.start++; end--;: Moves both pointers one step closer to the middle after each swap.
Exercise 3: Character Separator
Practice Problem: Take a string and print its individual characters separated by a space or tab.
Purpose: This exercise helps you practice iterating through a string one character at a time and formatting each character as part of a labeled sequence.
Given Input: text = "Code"
Expected Output:
Separating characters of "Code": C o d e Character separation completed successfully.
▼ Hint
- Use a
foreachloop to iterate through each character in the string. - Print each character followed by a space or tab using
Console.Write(). - Add a final
Console.WriteLine()after the loop to move to a new line.
▼ Solution & Explanation
Explanation:
class CharacterSeparator: Defines the class that holds the program’s entry point and separation logic.foreach (char ch in text): Iterates through each character of the string in order.Console.Write(ch + " "): Prints the character followed by a space, keeping all characters on the same line.Console.WriteLine(): Moves to a new line once all characters have been printed.
Exercise 4: Vowel & Consonant Counter
Practice Problem: Count the total number of vowels and consonants in a given sentence.
Purpose: This exercise helps you practice classifying characters within a longer piece of text, filtering out non-letter characters such as spaces and symbols while counting.
Given Input: sentence = "C# is a powerful programming language"
Expected Output:
Counting vowels and consonants in "C# is a powerful programming language": Vowels = 12 Consonants = 19 Vowel and consonant count completed successfully.
▼ Hint
- Convert the sentence to lowercase first so you only need to check one case.
- Loop through each character and compare it against the vowels a, e, i, o, u.
- If it is a letter but not a vowel, count it as a consonant; ignore spaces and symbols.
▼ Solution & Explanation
Explanation:
class VowelConsonantCounter: Defines the class that holds the program’s entry point and classification logic.sentence.ToLower(): Converts the sentence to lowercase so vowels and consonants only need to be checked in one case.ch == 'a' || ch == 'e' || ...: Checks if the current character is one of the five vowels.ch >= 'a' && ch <= 'z': Confirms the character is a letter before counting it as a consonant, automatically excluding spaces and the#symbol.
Exercise 5: Alphabet, Digit, and Special Character Counter
Practice Problem: Analyze a string and output the total count of alphabetic letters, numeric digits, and special symbols.
Purpose: This exercise helps you practice using the char.IsLetter() and char.IsDigit() methods inside a loop to classify each character in a string into one of three categories.
Given Input: text = "Hello123!@#"
Expected Output:
Analyzing characters in "Hello123!@#": Letters = 5 Digits = 3 Special Characters = 3 Character analysis completed successfully.
▼ Hint
- Loop through each character of the string using
foreach. - Use
char.IsLetter()andchar.IsDigit()to classify each character. - Any character that fails both checks is a special character.
▼ Solution & Explanation
Explanation:
class CharacterTypeCounter: Defines the class that holds the program’s entry point and classification logic.char.IsLetter(ch): Checks if the character is an alphabetic letter.char.IsDigit(ch): Checks if the character is a numeric digit.- Final
elseblock: Any character that is neither a letter nor a digit is counted as a special character.
Exercise 6: Case Converter
Practice Problem: Write a program that toggles the case of each character in a string, so uppercase becomes lowercase and lowercase becomes uppercase.
Purpose: This exercise helps you practice inspecting each character’s case with char.IsUpper() and char.IsLower() and converting it accordingly inside a loop.
Given Input: text = "Hello World"
Expected Output:
Toggling case of "Hello World": Toggled String: hELLO wORLD Case conversion completed successfully.
▼ Hint
- Convert the string into a character array using
ToCharArray(). - Loop through each character by index and check whether it is uppercase or lowercase using
char.IsUpper()andchar.IsLower(). - Convert uppercase characters to lowercase and lowercase characters to uppercase, then rebuild the string.
▼ Solution & Explanation
Explanation:
class CaseConverter: Defines the class that holds the program’s entry point and case-toggling logic.char[] characters = text.ToCharArray(): Converts the string into a character array so individual characters can be modified.char.IsUpper(characters[i]): Checks if the character is currently uppercase.char.ToLower(characters[i])/char.ToUpper(characters[i]): Converts the character to the opposite case.new string(characters): Rebuilds a string from the modified character array.
Exercise 7: Word Counter
Practice Problem: Count the total number of words in a string, assuming words are separated by spaces.
Purpose: This exercise helps you practice using a boolean flag alongside a loop to detect transitions between spaces and non-space characters, a common pattern for parsing text.
Given Input: text = "C# is a powerful programming language"
Expected Output:
Counting words in "C# is a powerful programming language": Word Count = 6 Word counting completed successfully.
▼ Hint
- Use a boolean flag to track whether you are currently inside a word.
- Loop through the string, and whenever a non-space character follows a space (or the start), increment the word count.
- Reset the flag whenever a space is encountered.
▼ Solution & Explanation
Explanation:
class WordCounter: Defines the class that holds the program’s entry point and word-counting logic.bool insideWord = false: Tracks whether the current position is inside a word or in the space between words.ch != ' ' && !insideWord: Detects the start of a new word, since the previous character was a space (or the string start) and the current one is not.wordCount++: Increments the count only at the start of each new word, not for every letter.ch == ' ': Marks that the current word has ended when a space is encountered.
Exercise 8: Sub-string Checker
Practice Problem: Check whether a specific substring exists inside a given string without using .Contains().
Purpose: This exercise helps you practice implementing a nested-loop pattern-matching approach, comparing a smaller string against every possible position in a larger one.
Given Input: text = "programming", sub = "gram"
Expected Output:
Checking if "gram" exists inside "programming": Result: "gram" was found inside "programming". Substring check completed successfully.
▼ Hint
- Use an outer loop to try every possible starting position in the main string.
- Use an inner loop to compare each character of the substring against the corresponding characters in the main string.
- If all characters match at a given position, the substring exists; if any character differs, move to the next starting position.
▼ Solution & Explanation
Explanation:
class SubstringChecker: Defines the class that holds the program’s entry point and pattern-matching logic.for (int i = 0; i <= text.Length - sub.Length; i++): Tries every possible starting position intextwheresubcould fit.for (int j = 0; j < sub.Length; j++): Compares each character ofsubagainst the corresponding character intextstarting at positioni.text[i + j] != sub[j]: If any character differs, the substring does not match at this position.break: Exits early once a mismatch or a full match is found, avoiding unnecessary comparisons.
Exercise 9: String Trimmer
Practice Problem: Remove all leading and trailing whitespace characters from a string manually using loops.
Purpose: This exercise helps you practice using two independent loops to locate the boundaries of meaningful content within a string before extracting it.
Given Input: text = " Hello World "
Expected Output:
Trimming whitespace from " Hello World ": Trimmed String: "Hello World" String trimming completed successfully.
▼ Hint
- Use a loop to move a start index forward as long as it points to a space.
- Use a loop to move an end index backward as long as it points to a space.
- Build a new string using only the characters between the adjusted start and end positions.
▼ Solution & Explanation
Explanation:
class StringTrimmer: Defines the class that holds the program's entry point and trimming logic.int start = 0; while (... text[start] == ' ') start++;: Moves the start index forward past any leading spaces.int end = text.Length - 1; while (... text[end] == ' ') end--;: Moves the end index backward past any trailing spaces.for (int i = start; i <= end; i++): Iterates only over the range between the first and last non-space characters.trimmed += text[i]: Builds the trimmed string one character at a time from the identified range.
Exercise 10: String Compactor (Manual Comparison)
Practice Problem: Compare two strings character by character to determine if they are identical, without using .Equals() or == on the strings themselves.
Purpose: This exercise helps you practice comparing two sequences element by element, first checking their lengths and then their individual characters, a pattern used in custom equality logic.
Given Input: text1 = "Hello", text2 = "Hello"
Expected Output:
Comparing "Hello" and "Hello": Result: The strings are identical. String comparison completed successfully.
▼ Hint
- First compare the lengths of both strings; if they differ, the strings cannot be identical.
- If lengths match, loop through each index and compare the corresponding characters.
- If any pair of characters differs, the strings are not identical; stop the loop early with
break.
▼ Solution & Explanation
Explanation:
class ManualStringComparer: Defines the class that holds the program's entry point and manual comparison logic.bool isIdentical = true: Assumes the strings are identical until proven otherwise.text1.Length != text2.Length: Strings of different lengths cannot be identical, so this check short-circuits the comparison.text1[i] != text2[i]: Uses character-by-character comparison instead of comparing the strings as whole objects.break: Stops comparing as soon as a mismatch is found.
Exercise 11: Sentence Reverser
Practice Problem: Reverse the order of words in a given sentence.
Purpose: This exercise helps you practice splitting a sentence into words with Split() and reassembling them in reverse order using a loop.
Given Input: sentence = "C# is fun"
Expected Output:
Reversing word order in "C# is fun": Reversed Sentence: fun is C# Sentence reversal completed successfully.
▼ Hint
- Split the sentence into an array of words using
Split(' '). - Loop through the array backward, from the last index to the first.
- Append each word to a result string, adding a space between words.
▼ Solution & Explanation
Explanation:
class SentenceReverser: Defines the class that holds the program's entry point and word-reversal logic.sentence.Split(' '): Splits the sentence into an array of individual words using spaces as separators.for (int i = words.Length - 1; i >= 0; i--): Iterates through the words array from the last word to the first.reversed += words[i]: Appends each word to the result string in reverse order.if (i != 0) reversed += " ": Adds a space between words but avoids a trailing space after the last word added.
Exercise 12: Character Frequency Counter
Practice Problem: Find and print the frequency of each character present in a string.
Purpose: This exercise helps you practice using nested loops with a tracking array to count occurrences of each unique character exactly once.
Given Input: text = "banana"
Expected Output:
Counting character frequency in "banana": 'b' = 1 'a' = 3 'n' = 2 Character frequency count completed successfully.
▼ Hint
- Use a boolean array to track which character positions have already been counted.
- For each uncounted character, use an inner loop to count how many times it appears in the rest of the string.
- Mark each matching position as counted so the same character isn't reported more than once.
▼ Solution & Explanation
Explanation:
class CharacterFrequencyCounter: Defines the class that holds the program's entry point and frequency-counting logic.bool[] counted = new bool[text.Length]: Tracks which positions have already been included in a frequency count, so each character is only reported once.if (counted[i]) continue;: Skips a position if that character has already been counted earlier in the string.for (int j = i; j < text.Length; j++): Scans the rest of the string for matches to the current character.counted[j] = true: Marks every matching position as counted so it is not processed again.
Exercise 13: Most Frequent Character
Practice Problem: Identify the character that appears the maximum number of times in a given string.
Purpose: This exercise helps you practice using nested loops to count occurrences of each character while tracking the running maximum, a common pattern in frequency-analysis problems.
Given Input: text = "success"
Expected Output: Most Frequent Character: 's' (3 times)
▼ Hint
- Use an outer loop to treat each character as a candidate.
- Use an inner loop to count how many times that character appears in the whole string.
- Keep track of the character with the highest frequency found so far.
▼ Solution & Explanation
Explanation:
class MostFrequentCharacterFinder: Defines the class that holds the program's entry point and frequency-comparison logic.char mostFrequentChar = text[0]; int maxFrequency = 0;: Initializes tracking variables before scanning the string.for (int i = 0; i < text.Length; i++): Treats each character position as a candidate for the most frequent character.for (int j = 0; j < text.Length; j++): Counts how many times the character at positioniappears anywhere in the string.if (frequency > maxFrequency): Updates the tracked maximum whenever a character with a higher frequency is found.
Exercise 14: Manual Substring Extractor
Practice Problem: Extract a substring from a given starting position up to a specified length without using .Substring().
Purpose: This exercise helps you practice building a new string by iterating over a specific index range, reinforcing how .Substring() works internally.
Given Input: text = "programming", startIndex = 3, length = 4
Expected Output:
Extracting 4 characters from "programming" starting at index 3: Extracted Substring: gram Substring extraction completed successfully.
▼ Hint
- Initialize an empty string to build the result.
- Use a loop that starts at
startIndexand runs forlengthiterations. - Append each character in that range to the result string.
▼ Solution & Explanation
Explanation:
class ManualSubstringExtractor: Defines the class that holds the program's entry point and extraction logic.string result = "": Initializes an empty string to build the extracted substring.for (int i = startIndex; i < startIndex + length; i++): Iterates only over the range of indices that fall within the desired substring.result += text[i]: Appends each character in that range to the result string.
Exercise 15: Alphabetical Sorter
Practice Problem: Read a string and sort its characters in ascending alphabetical order.
Purpose: This exercise helps you practice implementing a bubble sort with nested loops, comparing and swapping adjacent characters until the array is fully ordered.
Given Input: text = "dcba"
Expected Output:
Sorting characters of "dcba" alphabetically: Sorted String: abcd Alphabetical sorting completed successfully.
▼ Hint
- Convert the string into a character array using
ToCharArray(). - Use nested loops to implement a bubble sort, comparing adjacent characters.
- Swap any pair of characters that are out of order, and repeat until the array is fully sorted.
▼ Solution & Explanation
Explanation:
class AlphabeticalSorter: Defines the class that holds the program's entry point and sorting logic.char[] characters = text.ToCharArray(): Converts the string into a character array so elements can be swapped in place.for (int i = 0; i < characters.Length - 1; i++): Controls how many passes the bubble sort makes over the array.for (int j = 0; j < characters.Length - 1 - i; j++): Compares each pair of adjacent characters during a pass, shrinking the range as sorted elements settle at the end.characters[j] > characters[j + 1]: Checks if two adjacent characters are out of order, and swaps them using a temporary variable if so.
Exercise 16: Duplicate Remover
Practice Problem: Remove all duplicate characters from a string, keeping only their first occurrences.
Purpose: This exercise helps you practice building a result string incrementally while using an inner loop to check for characters that have already been included.
Given Input: text = "programming"
Expected Output:
Removing duplicate characters from "programming": Result: progamin Duplicate removal completed successfully.
▼ Hint
- Build up a result string starting empty.
- For each character in the original string, check if it already appears in the result using an inner loop.
- Only append the character to the result if it has not already been added.
▼ Solution & Explanation
Explanation:
class DuplicateRemover: Defines the class that holds the program's entry point and deduplication logic.string result = "": Initializes an empty string to build up the list of unique characters.for (int j = 0; j < result.Length; j++): Checks whether the current character already exists in the result built so far.if (!alreadyExists) result += text[i]: Appends the character only if it has not already been added, preserving the first occurrence.
Exercise 17: Title Case Converter
Practice Problem: Convert a given lowercase sentence so that the first letter of every word is capitalized.
Purpose: This exercise helps you practice using a boolean flag to detect word boundaries within a string and applying a transformation only at those positions.
Given Input: sentence = "the quick brown fox"
Expected Output:
Converting "the quick brown fox" to title case: Title Case: The Quick Brown Fox Title case conversion completed successfully.
▼ Hint
- Use a boolean flag, starting true, to track whether the next character should be capitalized.
- Loop through the characters, setting the flag to true whenever a space is found.
- Capitalize a character only when the flag is true, then reset the flag to false.
▼ Solution & Explanation
Explanation:
class TitleCaseConverter: Defines the class that holds the program's entry point and capitalization logic.bool capitalizeNext = true: Starts true so the first character of the sentence gets capitalized.characters[i] == ' ': Detects word boundaries, since a new word begins right after a space.char.ToUpper(characters[i]): Converts the first letter of each word to uppercase.capitalizeNext = false: Prevents the rest of the word from being capitalized after the first letter is handled.
Exercise 18: Palindrome Checker
Practice Problem: Determine if a string is a palindrome, ignoring case and spaces.
Purpose: This exercise helps you practice normalizing text before comparison and using the two-pointer technique to check for symmetry.
Given Input: text = "A man a plan a canal Panama"
Expected Output:
Checking if "A man a plan a canal Panama" is a palindrome: Result: The string is a palindrome. Palindrome check completed successfully.
▼ Hint
- Convert the string to lowercase and remove all spaces to build a cleaned version.
- Use two pointers, one at the start and one at the end of the cleaned string.
- Compare characters from both ends moving inward; if any pair differs, the string is not a palindrome.
▼ Solution & Explanation
Explanation:
class PalindromeChecker: Defines the class that holds the program's entry point and comparison logic.text.ToLower(): Converts the string to lowercase so the comparison ignores case differences.if (ch != ' ') cleaned += ch;: Builds a cleaned version of the string with spaces removed.int start = 0; int end = cleaned.Length - 1;: Sets up two pointers at opposite ends of the cleaned string.cleaned[start] != cleaned[end]: If any pair of characters from opposite ends doesn't match, the string is not a palindrome.
Exercise 19: Anagram Detector
Practice Problem: Check if two provided strings are anagrams of each other.
Purpose: This exercise helps you practice using a counting array to compare the letter composition of two strings, incrementing for one string and decrementing for the other.
Given Input: text1 = "listen", text2 = "silent"
Expected Output:
Checking if "listen" and "silent" are anagrams: Result: The strings are anagrams. Anagram check completed successfully.
▼ Hint
- If the strings have different lengths, they cannot be anagrams.
- Use a 26-element array to count how many times each letter appears in the first string.
- Subtract the counts for the second string, then check whether every count returns to 0.
▼ Solution & Explanation
Explanation:
class AnagramDetector: Defines the class that holds the program's entry point and letter-counting logic.int[] letterCounts = new int[26]: Creates a counter array with one slot for each letter of the alphabet.letterCounts[ch - 'a']++: Increments the count for each letter found in the first string.letterCounts[ch - 'a']--: Decrements the count for each letter found in the second string, canceling out matching letters.if (count != 0): If any letter's count isn't 0 after both strings are processed, the strings used different letters or different frequencies, so they aren't anagrams.
Exercise 20: String Padding Creator
Practice Problem: Implement manual left and right padding for a string to reach a target length using a specific pad character.
Purpose: This exercise helps you practice growing a string incrementally with a loop until it reaches a target length, adding characters to either end.
Given Input: text = "42", targetLength = 6, padChar = '0'
Expected Output:
Padding "42" to a length of 6: Left Padded: 000042 Right Padded: 420000 String padding completed successfully.
▼ Hint
- Start with a copy of the original string for both the left-padded and right-padded results.
- Use a
whileloop that continues as long as the string's length is less than the target length. - For left padding, add the pad character to the front; for right padding, add it to the end.
▼ Solution & Explanation
Explanation:
class StringPaddingCreator: Defines the class that holds the program's entry point and padding logic.string leftPadded = text: Starts with a copy of the original string to build the left-padded version.while (leftPadded.Length < targetLength): Continues adding padding characters until the target length is reached.leftPadded = padChar + leftPadded: Prepends the pad character to the front of the string on each iteration.rightPadded = rightPadded + padChar: Appends the pad character to the end of the string on each iteration for right padding.
Exercise 21: Find All Substrings
Practice Problem: Generate and print all possible contiguous substrings of a given string.
Purpose: This exercise helps you practice using nested loops to generate every possible start and end position pair within a string, a foundational pattern for many string and array problems.
Given Input: text = "abc"
Expected Output:
Generating all substrings of "abc": a ab abc b bc c Substring generation completed successfully.
▼ Hint
- Use an outer loop for the starting index of each substring.
- Use an inner loop for the ending index, starting from the same position as the outer loop.
- Extract and print the substring defined by each pair of start and end indices.
▼ Solution & Explanation
Explanation:
class SubstringGenerator: Defines the class that holds the program's entry point and substring-generation logic.for (int i = 0; i < text.Length; i++): Selects the starting position of each substring.for (int j = i; j < text.Length; j++): Selects the ending position of each substring, always at or after the starting position.text.Substring(i, j - i + 1): Extracts the substring starting at indexiwith a length that reaches indexj.
Exercise 22: Longest Common Prefix
Practice Problem: Given an array of strings, find the longest common prefix string among them.
Purpose: This exercise helps you practice comparing a candidate value against multiple items in a collection, stopping as soon as any item breaks the match.
Given Input: words = {"flower", "flow", "flight"}
Expected Output: Longest Common Prefix: "fl"
▼ Hint
- Use the first word as your initial reference for the prefix.
- Loop through its characters one at a time, comparing each character against the same position in every other word.
- Stop as soon as a character does not match or a word runs out of characters at that position.
▼ Solution & Explanation
Explanation:
class LongestCommonPrefixFinder: Defines the class that holds the program's entry point and prefix-matching logic.string firstWord = words[0]: Uses the first word as the initial candidate, since the common prefix can never be longer than the shortest word.foreach (string word in words): Compares the current character position against every other word in the array.i >= word.Length || word[i] != currentChar: Stops the match if another word is too short or has a different character at that position.break(outer loop): Stops adding to the prefix as soon as any word disagrees at the current position.
Exercise 23: First Non-Repeated Character
Practice Problem: Scan a string from left to right and find the very first character that does not repeat.
Purpose: This exercise helps you practice using nested loops to count character occurrences while preserving the original left-to-right order of the string.
Given Input: text = "swiss"
Expected Output:
Finding the first non-repeated character in "swiss": First Non-Repeated Character: 'w' Search completed successfully.
▼ Hint
- Loop through the string from left to right.
- For each character, use an inner loop to count its total occurrences in the string.
- Return the first character found with a count of exactly 1, and stop searching immediately.
▼ Solution & Explanation
Explanation:
class FirstNonRepeatedCharacterFinder: Defines the class that holds the program's entry point and search logic.for (int i = 0; i < text.Length; i++): Checks each character in the order it appears in the string.for (int j = 0; j < text.Length; j++): Counts how many times that character appears anywhere in the string.if (count == 1): Identifies a character that appears exactly once.break: Stops immediately once the first non-repeated character is found, since later characters don't matter.
Exercise 24: String to Integer (Manual Parse)
Practice Problem: Convert a numerical string into an actual int variable without using int.Parse() or Convert.ToInt32().
Purpose: This exercise helps you practice building a number digit by digit from its character representation, including handling an optional leading negative sign.
Given Input: text = "-1234"
Expected Output:
Parsing "-1234" into an integer: Parsed Integer: -1234 Manual parsing completed successfully.
▼ Hint
- Check if the first character is a minus sign, and if so, remember that the number is negative and skip that character.
- Loop through the remaining characters, converting each one to its digit value using
char - '0'. - Build the number using
result = result * 10 + digit, then negate it at the end if needed.
▼ Solution & Explanation
Explanation:
class ManualIntegerParser: Defines the class that holds the program's entry point and parsing logic.if (text[0] == '-'): Detects a leading negative sign and records it, then skips it during digit processing.text[i] - '0': Converts the character digit into its numeric value.result = result * 10 + digit: Shifts the previously built number one place to the left and adds the new digit, building the number from left to right.if (isNegative) result = -result;: Applies the negative sign to the final result if one was detected at the start.
Exercise 25: Run-Length Encoding (RLE)
Practice Problem: Implement a simple form of data compression where runs of repeated characters are stored as a single character and count.
Purpose: This exercise helps you practice using a nested loop pattern to measure consecutive runs of the same value, a technique used in basic compression algorithms.
Given Input: text = "aabbbcccc"
Expected Output:
Encoding "aabbbcccc" using run-length encoding: Encoded String: a2b3c4 Run-length encoding completed successfully.
▼ Hint
- Use an outer loop that processes the string from left to right, one run at a time.
- Use an inner loop to count how many times the current character repeats consecutively.
- Append the character followed by its count to the result string, then continue from the next different character.
▼ Solution & Explanation
Explanation:
class RunLengthEncoder: Defines the class that holds the program's entry point and encoding logic.char currentChar = text[i]: Marks the character whose run is currently being measured.while (i < text.Length && text[i] == currentChar): Keeps counting and advancing as long as the same character repeats.encoded += currentChar.ToString() + count: Appends the character and how many times it repeated to the result string.- Outer
while (i < text.Length): Continues the process from the next differing character until the entire string has been processed.
Exercise 26: Valid Parentheses
Practice Problem: Check if a string containing just the characters '(', ')', '{', '}', '[' and ']' is structurally valid.
Purpose: This exercise helps you practice using a stack inside a loop to track unmatched opening brackets and verify that every closing bracket matches the most recent unmatched opener.
Given Input: text = "{[()]}"
Expected Output:
Checking if "{[()]}" has valid parentheses:
Result: The string is valid.
Parentheses check completed successfully.
▼ Hint
- Use a stack to keep track of opening brackets as you encounter them.
- When you encounter a closing bracket, pop from the stack and check that it matches the expected opening bracket.
- If the stack is empty when a closing bracket appears, or if brackets remain on the stack at the end, the string is not valid.
▼ Solution & Explanation
Explanation:
class ValidParenthesesChecker: Defines the class that holds the program's entry point and bracket-matching logic.Stack<char> stack = new Stack<char>(): Creates a stack to keep track of unmatched opening brackets in order.stack.Push(ch): Pushes any opening bracket onto the stack.stack.Count == 0: If a closing bracket appears with no opening bracket on the stack, the string is immediately invalid.char top = stack.Pop(): Removes the most recent unmatched opening bracket to compare against the current closing bracket.stack.Count != 0(after the loop): If any opening brackets remain unmatched at the end, the string is not valid.
Exercise 27: URL Encoder
Practice Problem: Replace all spaces in a string with "%20" efficiently using a StringBuilder.
Purpose: This exercise helps you practice using StringBuilder to build a result efficiently inside a loop, avoiding the performance cost of repeated string concatenation.
Given Input: text = "Hello World Wide Web"
Expected Output:
Encoding spaces in "Hello World Wide Web": Encoded URL: Hello%20World%20Wide%20Web URL encoding completed successfully.
▼ Hint
- Create a
StringBuilderto build the result efficiently. - Loop through each character of the original string.
- Append
"%20"whenever a space is found, and append the character unchanged otherwise.
▼ Solution & Explanation
Explanation:
class UrlEncoder: Defines the class that holds the program's entry point and encoding logic.StringBuilder builder = new StringBuilder(): Creates a mutable buffer for efficiently building the result string without repeated string concatenation.builder.Append("%20"): Appends the URL-encoded representation of a space instead of the space itself.builder.Append(ch): Appends any other character unchanged.builder.ToString(): Converts the completed buffer into a regular string once all characters have been processed.
Exercise 28: String Rotation Checker
Practice Problem: Given two strings s1 and s2, check if s2 is a rotated version of s1.
Purpose: This exercise helps you practice a classic trick where concatenating a string with itself lets you search for any rotation using a straightforward substring search.
Given Input: s1 = "waterbottle", s2 = "erbottlewat"
Expected Output:
Checking if "erbottlewat" is a rotation of "waterbottle": Result: The strings are rotations of each other. Rotation check completed successfully.
▼ Hint
- First check that both strings have the same length.
- Concatenate
s1with itself; every rotation ofs1will appear somewhere inside this doubled string. - Search for
s2inside the doubled string using a nested loop, similar to a substring search.
▼ Solution & Explanation
Explanation:
class StringRotationChecker: Defines the class that holds the program's entry point and rotation-checking logic.if (s1.Length == s2.Length): Two strings of different lengths can never be rotations of each other.string combined = s1 + s1: Concatenatings1with itself creates a string that contains every possible rotation ofs1as a substring.for (int i = 0; i <= combined.Length - s2.Length; i++): Tries every possible starting position within the combined string.if (match) isRotation = true; break;: Confirms a rotation match was found and stops searching further.
Exercise 29: Caesar Cipher Implementation
Practice Problem: Create an encryption scheme that shifts every letter in a string by a fixed number of positions down the alphabet.
Purpose: This exercise helps you practice mapping characters to numeric positions, applying an offset with the modulus operator to wrap around the alphabet, and converting back to characters.
Given Input: text = "Hello World", shift = 3
Expected Output:
Encrypting "Hello World" with a shift of 3: Encrypted Text: Khoor Zruog Caesar cipher encryption completed successfully.
▼ Hint
- Loop through each character and check whether it is an uppercase or lowercase letter.
- Convert the letter to a zero-based position in the alphabet, add the shift amount, and use the modulus operator to wrap around after 'Z' or 'z'.
- Convert the shifted position back into a character, leaving any non-letter characters unchanged.
▼ Solution & Explanation
Explanation:
class CaesarCipherEncoder: Defines the class that holds the program's entry point and shifting logic.char.IsUpper(ch)/char.IsLower(ch): Determines whether a character is an uppercase or lowercase letter, so its case can be preserved after shifting.ch - 'A'(or'a'): Converts the letter to a zero-based position in the alphabet.(... + shift) % 26: Shifts the position forward by the given amount, wrapping back to the start of the alphabet if it goes past 'Z' or 'z'.- Non-letter characters: Left unchanged, since they don't match either the
IsUpperorIsLowercondition.
Exercise 30: Longest Substring Without Repeating Characters
Practice Problem: Find the length of the longest substring in a given string that contains no duplicate characters.
Purpose: This exercise helps you practice the sliding window technique, expanding and shrinking a window over a string with two index variables and a set that tracks the window's contents.
Given Input: text = "abcabcbb"
Expected Output:
Finding the longest substring without repeating characters in "abcabcbb": Longest Substring Length = 3 Search completed successfully.
▼ Hint
- Use two index variables,
leftandright, to represent a sliding window over the string. - Use a
HashSetto track which characters are currently inside the window. - Expand the window from the right; whenever a duplicate is found, shrink it from the left until the duplicate is removed, and track the maximum window size seen.
▼ Solution & Explanation
Explanation:
class LongestUniqueSubstringFinder: Defines the class that holds the program's entry point and sliding-window logic.HashSet<char> window = new HashSet<char>(): Keeps track of the unique characters currently inside the sliding window.for (int right = 0; right < text.Length; right++): Expands the window one character at a time from the right.while (window.Contains(text[right])): Shrinks the window from the left whenever the new character would create a duplicate.right - left + 1: Calculates the current window's length, which is compared against the running maximum.

Leave a Reply