PYnative

Python Programming

  • Learn Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • Quizzes
  • Code Editor ▼
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » C# Exercises » C# String Exercises: 30 Coding Problems with Solutions

C# String Exercises: 30 Coding Problems with Solutions

Updated on: July 15, 2026 | Leave a Comment

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 foreach loop 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
using System;

namespace StringUtilities
{
    class LengthCalculator
    {
        static void Main(string[] args)
        {
            string text = "Programming";
            int length = 0;

            Console.WriteLine($"Calculating length of \"{text}\":");

            foreach (char ch in text)
            {
                length++;
            }

            Console.WriteLine($"Length = {length}");
            Console.WriteLine("Length calculation completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class StringReverser
    {
        static void Main(string[] args)
        {
            string text = "hello";
            char[] characters = text.ToCharArray();
            int start = 0;
            int end = characters.Length - 1;

            Console.WriteLine($"Reversing the string \"{text}\":");

            while (start < end)
            {
                char temp = characters[start];
                characters[start] = characters[end];
                characters[end] = temp;
                start++;
                end--;
            }

            string reversed = new string(characters);

            Console.WriteLine($"Reversed String: {reversed}");
            Console.WriteLine("String reversal completed successfully.");
        }
    }
}Code language: C# (cs)

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 foreach loop 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
using System;

namespace StringUtilities
{
    class CharacterSeparator
    {
        static void Main(string[] args)
        {
            string text = "Code";

            Console.WriteLine($"Separating characters of \"{text}\":");

            foreach (char ch in text)
            {
                Console.Write(ch + " ");
            }

            Console.WriteLine();
            Console.WriteLine("Character separation completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class VowelConsonantCounter
    {
        static void Main(string[] args)
        {
            string sentence = "C# is a powerful programming language";
            int vowelCount = 0;
            int consonantCount = 0;

            Console.WriteLine($"Counting vowels and consonants in \"{sentence}\":");

            foreach (char ch in sentence.ToLower())
            {
                if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                {
                    vowelCount++;
                }
                else if (ch >= 'a' && ch <= 'z')
                {
                    consonantCount++;
                }
            }

            Console.WriteLine($"Vowels = {vowelCount}");
            Console.WriteLine($"Consonants = {consonantCount}");
            Console.WriteLine("Vowel and consonant count completed successfully.");
        }
    }
}Code language: C# (cs)

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() and char.IsDigit() to classify each character.
  • Any character that fails both checks is a special character.
▼ Solution & Explanation
using System;

namespace StringUtilities
{
    class CharacterTypeCounter
    {
        static void Main(string[] args)
        {
            string text = "Hello123!@#";
            int letterCount = 0;
            int digitCount = 0;
            int specialCount = 0;

            Console.WriteLine($"Analyzing characters in \"{text}\":");

            foreach (char ch in text)
            {
                if (char.IsLetter(ch))
                {
                    letterCount++;
                }
                else if (char.IsDigit(ch))
                {
                    digitCount++;
                }
                else
                {
                    specialCount++;
                }
            }

            Console.WriteLine($"Letters = {letterCount}");
            Console.WriteLine($"Digits = {digitCount}");
            Console.WriteLine($"Special Characters = {specialCount}");
            Console.WriteLine("Character analysis completed successfully.");
        }
    }
}Code language: C# (cs)

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 else block: 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() and char.IsLower().
  • Convert uppercase characters to lowercase and lowercase characters to uppercase, then rebuild the string.
▼ Solution & Explanation
using System;

namespace StringUtilities
{
    class CaseConverter
    {
        static void Main(string[] args)
        {
            string text = "Hello World";
            char[] characters = text.ToCharArray();

            Console.WriteLine($"Toggling case of \"{text}\":");

            for (int i = 0; i < characters.Length; i++)
            {
                if (char.IsUpper(characters[i]))
                {
                    characters[i] = char.ToLower(characters[i]);
                }
                else if (char.IsLower(characters[i]))
                {
                    characters[i] = char.ToUpper(characters[i]);
                }
            }

            string toggled = new string(characters);

            Console.WriteLine($"Toggled String: {toggled}");
            Console.WriteLine("Case conversion completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class WordCounter
    {
        static void Main(string[] args)
        {
            string text = "C# is a powerful programming language";
            int wordCount = 0;
            bool insideWord = false;

            Console.WriteLine($"Counting words in \"{text}\":");

            foreach (char ch in text)
            {
                if (ch != ' ' && !insideWord)
                {
                    insideWord = true;
                    wordCount++;
                }
                else if (ch == ' ')
                {
                    insideWord = false;
                }
            }

            Console.WriteLine($"Word Count = {wordCount}");
            Console.WriteLine("Word counting completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;
namespace StringUtilities
{
    class SubstringChecker
    {
        static void Main(string[] args)
        {
            string text = "programming";
            string sub = "gram";
            bool found = false;
            Console.WriteLine($"Checking if \"{sub}\" exists inside \"{text}\":");
            for (int i = 0; i <= text.Length - sub.Length; i++)
            {
                bool match = true;
                for (int j = 0; j < sub.Length; j++)
                {
                    if (text[i + j] != sub[j])
                    {
                        match = false;
                        break;
                    }
                }
                if (match)
                {
                    found = true;
                    break;
                }
            }
            if (found)
            {
                Console.WriteLine($"Result: \"{sub}\" was found inside \"{text}\".");
            }
            else
            {
                Console.WriteLine($"Result: \"{sub}\" was not found inside \"{text}\".");
            }
            Console.WriteLine("Substring check completed successfully.");
        }
    }
}Code language: C# (cs)

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 in text where sub could fit.
  • for (int j = 0; j < sub.Length; j++): Compares each character of sub against the corresponding character in text starting at position i.
  • 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
using System;

namespace StringUtilities
{
    class StringTrimmer
    {
        static void Main(string[] args)
        {
            string text = "   Hello World   ";

            Console.WriteLine($"Trimming whitespace from \"{text}\":");

            int start = 0;
            while (start < text.Length && text[start] == ' ')
            {
                start++;
            }

            int end = text.Length - 1;
            while (end >= 0 && text[end] == ' ')
            {
                end--;
            }

            string trimmed = "";
            for (int i = start; i <= end; i++)
            {
                trimmed += text[i];
            }

            Console.WriteLine($"Trimmed String: \"{trimmed}\"");
            Console.WriteLine("String trimming completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class ManualStringComparer
    {
        static void Main(string[] args)
        {
            string text1 = "Hello";
            string text2 = "Hello";
            bool isIdentical = true;

            Console.WriteLine($"Comparing \"{text1}\" and \"{text2}\":");

            if (text1.Length != text2.Length)
            {
                isIdentical = false;
            }
            else
            {
                for (int i = 0; i < text1.Length; i++)
                {
                    if (text1[i] != text2[i])
                    {
                        isIdentical = false;
                        break;
                    }
                }
            }

            if (isIdentical)
            {
                Console.WriteLine("Result: The strings are identical.");
            }
            else
            {
                Console.WriteLine("Result: The strings are not identical.");
            }

            Console.WriteLine("String comparison completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class SentenceReverser
    {
        static void Main(string[] args)
        {
            string sentence = "C# is fun";
            string[] words = sentence.Split(' ');
            string reversed = "";

            Console.WriteLine($"Reversing word order in \"{sentence}\":");

            for (int i = words.Length - 1; i >= 0; i--)
            {
                reversed += words[i];
                if (i != 0)
                {
                    reversed += " ";
                }
            }

            Console.WriteLine($"Reversed Sentence: {reversed}");
            Console.WriteLine("Sentence reversal completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;
namespace StringUtilities
{
    class CharacterFrequencyCounter
    {
        static void Main(string[] args)
        {
            string text = "banana";
            bool[] counted = new bool[text.Length];
            Console.WriteLine($"Counting character frequency in \"{text}\":");
            for (int i = 0; i < text.Length; i++)
            {
                if (counted[i])
                {
                    continue;
                }
                int frequency = 0;
                for (int j = i; j < text.Length; j++)
                {
                    if (text[j] == text[i])
                    {
                        frequency++;
                        counted[j] = true;
                    }
                }
                Console.WriteLine($"'{text[i]}' = {frequency}");
            }
            Console.WriteLine("Character frequency count completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class MostFrequentCharacterFinder
    {
        static void Main(string[] args)
        {
            string text = "success";
            char mostFrequentChar = text[0];
            int maxFrequency = 0;

            Console.WriteLine($"Finding the most frequent character in \"{text}\":");

            for (int i = 0; i < text.Length; i++)
            {
                int frequency = 0;

                for (int j = 0; j < text.Length; j++)
                {
                    if (text[j] == text[i])
                    {
                        frequency++;
                    }
                }

                if (frequency > maxFrequency)
                {
                    maxFrequency = frequency;
                    mostFrequentChar = text[i];
                }
            }

            Console.WriteLine($"Most Frequent Character: '{mostFrequentChar}' ({maxFrequency} times)");
            Console.WriteLine("Most frequent character search completed successfully.");
        }
    }
}Code language: C# (cs)

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 position i appears 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 startIndex and runs for length iterations.
  • Append each character in that range to the result string.
▼ Solution & Explanation
using System;

namespace StringUtilities
{
    class ManualSubstringExtractor
    {
        static void Main(string[] args)
        {
            string text = "programming";
            int startIndex = 3;
            int length = 4;
            string result = "";

            Console.WriteLine($"Extracting {length} characters from \"{text}\" starting at index {startIndex}:");

            for (int i = startIndex; i < startIndex + length; i++)
            {
                result += text[i];
            }

            Console.WriteLine($"Extracted Substring: {result}");
            Console.WriteLine("Substring extraction completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class AlphabeticalSorter
    {
        static void Main(string[] args)
        {
            string text = "dcba";
            char[] characters = text.ToCharArray();

            Console.WriteLine($"Sorting characters of \"{text}\" alphabetically:");

            for (int i = 0; i < characters.Length - 1; i++)
            {
                for (int j = 0; j < characters.Length - 1 - i; j++)
                {
                    if (characters[j] > characters[j + 1])
                    {
                        char temp = characters[j];
                        characters[j] = characters[j + 1];
                        characters[j + 1] = temp;
                    }
                }
            }

            string sorted = new string(characters);

            Console.WriteLine($"Sorted String: {sorted}");
            Console.WriteLine("Alphabetical sorting completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class DuplicateRemover
    {
        static void Main(string[] args)
        {
            string text = "programming";
            string result = "";

            Console.WriteLine($"Removing duplicate characters from \"{text}\":");

            for (int i = 0; i < text.Length; i++)
            {
                bool alreadyExists = false;

                for (int j = 0; j < result.Length; j++)
                {
                    if (result[j] == text[i])
                    {
                        alreadyExists = true;
                        break;
                    }
                }

                if (!alreadyExists)
                {
                    result += text[i];
                }
            }

            Console.WriteLine($"Result: {result}");
            Console.WriteLine("Duplicate removal completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class TitleCaseConverter
    {
        static void Main(string[] args)
        {
            string sentence = "the quick brown fox";
            char[] characters = sentence.ToCharArray();
            bool capitalizeNext = true;

            Console.WriteLine($"Converting \"{sentence}\" to title case:");

            for (int i = 0; i < characters.Length; i++)
            {
                if (characters[i] == ' ')
                {
                    capitalizeNext = true;
                }
                else if (capitalizeNext)
                {
                    characters[i] = char.ToUpper(characters[i]);
                    capitalizeNext = false;
                }
            }

            string titleCased = new string(characters);

            Console.WriteLine($"Title Case: {titleCased}");
            Console.WriteLine("Title case conversion completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class PalindromeChecker
    {
        static void Main(string[] args)
        {
            string text = "A man a plan a canal Panama";
            string cleaned = "";

            Console.WriteLine($"Checking if \"{text}\" is a palindrome:");

            foreach (char ch in text.ToLower())
            {
                if (ch != ' ')
                {
                    cleaned += ch;
                }
            }

            bool isPalindrome = true;
            int start = 0;
            int end = cleaned.Length - 1;

            while (start < end)
            {
                if (cleaned[start] != cleaned[end])
                {
                    isPalindrome = false;
                    break;
                }
                start++;
                end--;
            }

            if (isPalindrome)
            {
                Console.WriteLine("Result: The string is a palindrome.");
            }
            else
            {
                Console.WriteLine("Result: The string is not a palindrome.");
            }

            Console.WriteLine("Palindrome check completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class AnagramDetector
    {
        static void Main(string[] args)
        {
            string text1 = "listen";
            string text2 = "silent";
            bool isAnagram = true;

            Console.WriteLine($"Checking if \"{text1}\" and \"{text2}\" are anagrams:");

            if (text1.Length != text2.Length)
            {
                isAnagram = false;
            }
            else
            {
                int[] letterCounts = new int[26];

                foreach (char ch in text1.ToLower())
                {
                    letterCounts[ch - 'a']++;
                }

                foreach (char ch in text2.ToLower())
                {
                    letterCounts[ch - 'a']--;
                }

                foreach (int count in letterCounts)
                {
                    if (count != 0)
                    {
                        isAnagram = false;
                        break;
                    }
                }
            }

            if (isAnagram)
            {
                Console.WriteLine("Result: The strings are anagrams.");
            }
            else
            {
                Console.WriteLine("Result: The strings are not anagrams.");
            }

            Console.WriteLine("Anagram check completed successfully.");
        }
    }
}Code language: C# (cs)

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 while loop 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
using System;

namespace StringUtilities
{
    class StringPaddingCreator
    {
        static void Main(string[] args)
        {
            string text = "42";
            int targetLength = 6;
            char padChar = '0';

            Console.WriteLine($"Padding \"{text}\" to a length of {targetLength}:");

            string leftPadded = text;
            while (leftPadded.Length < targetLength)
            {
                leftPadded = padChar + leftPadded;
            }

            string rightPadded = text;
            while (rightPadded.Length < targetLength)
            {
                rightPadded = rightPadded + padChar;
            }

            Console.WriteLine($"Left Padded: {leftPadded}");
            Console.WriteLine($"Right Padded: {rightPadded}");
            Console.WriteLine("String padding completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class SubstringGenerator
    {
        static void Main(string[] args)
        {
            string text = "abc";

            Console.WriteLine($"Generating all substrings of \"{text}\":");

            for (int i = 0; i < text.Length; i++)
            {
                for (int j = i; j < text.Length; j++)
                {
                    string sub = text.Substring(i, j - i + 1);
                    Console.WriteLine(sub);
                }
            }

            Console.WriteLine("Substring generation completed successfully.");
        }
    }
}Code language: C# (cs)

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 index i with a length that reaches index j.

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
using System;

namespace StringUtilities
{
    class LongestCommonPrefixFinder
    {
        static void Main(string[] args)
        {
            string[] words = { "flower", "flow", "flight" };
            string prefix = "";

            Console.WriteLine("Finding the longest common prefix:");

            if (words.Length > 0)
            {
                string firstWord = words[0];

                for (int i = 0; i < firstWord.Length; i++)
                {
                    char currentChar = firstWord[i];
                    bool allMatch = true;

                    foreach (string word in words)
                    {
                        if (i >= word.Length || word[i] != currentChar)
                        {
                            allMatch = false;
                            break;
                        }
                    }

                    if (!allMatch)
                    {
                        break;
                    }

                    prefix += currentChar;
                }
            }

            Console.WriteLine($"Longest Common Prefix: \"{prefix}\"");
            Console.WriteLine("Prefix search completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class FirstNonRepeatedCharacterFinder
    {
        static void Main(string[] args)
        {
            string text = "swiss";

            Console.WriteLine($"Finding the first non-repeated character in \"{text}\":");

            char result = '\0';
            bool found = false;

            for (int i = 0; i < text.Length; i++)
            {
                int count = 0;

                for (int j = 0; j < text.Length; j++)
                {
                    if (text[j] == text[i])
                    {
                        count++;
                    }
                }

                if (count == 1)
                {
                    result = text[i];
                    found = true;
                    break;
                }
            }

            if (found)
            {
                Console.WriteLine($"First Non-Repeated Character: '{result}'");
            }
            else
            {
                Console.WriteLine("Result: No non-repeated character found.");
            }

            Console.WriteLine("Search completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class ManualIntegerParser
    {
        static void Main(string[] args)
        {
            string text = "-1234";
            int result = 0;
            bool isNegative = false;
            int startIndex = 0;

            Console.WriteLine($"Parsing \"{text}\" into an integer:");

            if (text[0] == '-')
            {
                isNegative = true;
                startIndex = 1;
            }

            for (int i = startIndex; i < text.Length; i++)
            {
                int digit = text[i] - '0';
                result = result * 10 + digit;
            }

            if (isNegative)
            {
                result = -result;
            }

            Console.WriteLine($"Parsed Integer: {result}");
            Console.WriteLine("Manual parsing completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace StringUtilities
{
    class RunLengthEncoder
    {
        static void Main(string[] args)
        {
            string text = "aabbbcccc";
            string encoded = "";

            Console.WriteLine($"Encoding \"{text}\" using run-length encoding:");

            int i = 0;
            while (i < text.Length)
            {
                char currentChar = text[i];
                int count = 0;

                while (i < text.Length && text[i] == currentChar)
                {
                    count++;
                    i++;
                }

                encoded += currentChar.ToString() + count;
            }

            Console.WriteLine($"Encoded String: {encoded}");
            Console.WriteLine("Run-length encoding completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;
using System.Collections.Generic;

namespace StringUtilities
{
    class ValidParenthesesChecker
    {
        static void Main(string[] args)
        {
            string text = "{[()]}";
            Stack<char> stack = new Stack<char>();
            bool isValid = true;

            Console.WriteLine($"Checking if \"{text}\" has valid parentheses:");

            foreach (char ch in text)
            {
                if (ch == '(' || ch == '{' || ch == '[')
                {
                    stack.Push(ch);
                }
                else
                {
                    if (stack.Count == 0)
                    {
                        isValid = false;
                        break;
                    }

                    char top = stack.Pop();

                    if ((ch == ')' && top != '(') ||
                        (ch == '}' && top != '{') ||
                        (ch == ']' && top != '['))
                    {
                        isValid = false;
                        break;
                    }
                }
            }

            if (stack.Count != 0)
            {
                isValid = false;
            }

            if (isValid)
            {
                Console.WriteLine("Result: The string is valid.");
            }
            else
            {
                Console.WriteLine("Result: The string is not valid.");
            }

            Console.WriteLine("Parentheses check completed successfully.");
        }
    }
}</char></char>Code language: C# (cs)

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 StringBuilder to 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
using System;
using System.Text;

namespace StringUtilities
{
    class UrlEncoder
    {
        static void Main(string[] args)
        {
            string text = "Hello World Wide Web";
            StringBuilder builder = new StringBuilder();

            Console.WriteLine($"Encoding spaces in \"{text}\":");

            foreach (char ch in text)
            {
                if (ch == ' ')
                {
                    builder.Append("%20");
                }
                else
                {
                    builder.Append(ch);
                }
            }

            string encoded = builder.ToString();

            Console.WriteLine($"Encoded URL: {encoded}");
            Console.WriteLine("URL encoding completed successfully.");
        }
    }
}Code language: C# (cs)

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 s1 with itself; every rotation of s1 will appear somewhere inside this doubled string.
  • Search for s2 inside the doubled string using a nested loop, similar to a substring search.
▼ Solution & Explanation
using System;

namespace StringUtilities
{
    class StringRotationChecker
    {
        static void Main(string[] args)
        {
            string s1 = "waterbottle";
            string s2 = "erbottlewat";
            bool isRotation = false;

            Console.WriteLine($"Checking if \"{s2}\" is a rotation of \"{s1}\":");

            if (s1.Length == s2.Length)
            {
                string combined = s1 + s1;

                for (int i = 0; i <= combined.Length - s2.Length; i++)
                {
                    bool match = true;

                    for (int j = 0; j < s2.Length; j++)
                    {
                        if (combined[i + j] != s2[j])
                        {
                            match = false;
                            break;
                        }
                    }

                    if (match)
                    {
                        isRotation = true;
                        break;
                    }
                }
            }

            if (isRotation)
            {
                Console.WriteLine("Result: The strings are rotations of each other.");
            }
            else
            {
                Console.WriteLine("Result: The strings are not rotations of each other.");
            }

            Console.WriteLine("Rotation check completed successfully.");
        }
    }
}Code language: C# (cs)

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: Concatenating s1 with itself creates a string that contains every possible rotation of s1 as 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
using System;

namespace StringUtilities
{
    class CaesarCipherEncoder
    {
        static void Main(string[] args)
        {
            string text = "Hello World";
            int shift = 3;
            char[] characters = text.ToCharArray();

            Console.WriteLine($"Encrypting \"{text}\" with a shift of {shift}:");

            for (int i = 0; i < characters.Length; i++)
            {
                char ch = characters[i];

                if (char.IsUpper(ch))
                {
                    characters[i] = (char)(((ch - 'A' + shift) % 26) + 'A');
                }
                else if (char.IsLower(ch))
                {
                    characters[i] = (char)(((ch - 'a' + shift) % 26) + 'a');
                }
            }

            string encrypted = new string(characters);

            Console.WriteLine($"Encrypted Text: {encrypted}");
            Console.WriteLine("Caesar cipher encryption completed successfully.");
        }
    }
}Code language: C# (cs)

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 IsUpper or IsLower condition.

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, left and right, to represent a sliding window over the string.
  • Use a HashSet to 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
using System;
using System.Collections.Generic;

namespace StringUtilities
{
    class LongestUniqueSubstringFinder
    {
        static void Main(string[] args)
        {
            string text = "abcabcbb";
            HashSet<char> window = new HashSet<char>();
            int left = 0;
            int maxLength = 0;

            Console.WriteLine($"Finding the longest substring without repeating characters in \"{text}\":");

            for (int right = 0; right < text.Length; right++)
            {
                while (window.Contains(text[right]))
                {
                    window.Remove(text[left]);
                    left++;
                }

                window.Add(text[right]);

                int currentLength = right - left + 1;
                if (currentLength > maxLength)
                {
                    maxLength = currentLength;
                }
            }

            Console.WriteLine($"Longest Substring Length = {maxLength}");
            Console.WriteLine("Search completed successfully.");
        }
    }
}</char></char>Code language: C# (cs)

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.

Filed Under: C# Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

C# Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: C# Exercises
TweetF  sharein  shareP  Pin

  C# Exercises

  • C# Exercise for Beginners
  • C# Loops Exercise
  • C# Array Exercise
  • C# String Exercise
  • C# OOP Exercise
  • C# Structs, Records and Enums Exercise
  • C# Collections Exercise
  • C# List Exercise
  • C# Dictionary Exercise
  • C# LINQ Exercise
  • C# Exception Handling Exercise
  • C# File Handling Exercise
  • C# Date and Time Exercise
  • C# Generics Exercise
  • C# Lambda Expressions Exercise
  • C# Delegates and Events Exercise
  • C# Extension Methods Exercise
  • C# Regex Exercise
  • C# Pattern Matching Exercise
  • C# Iterators and Yield Exercise
  • C# Indexers and Operator Overloading Exercise
  • C# Random Data Generation Exercise

All Coding Exercises

Python Exercises C Exercises C++ Exercises Java Exercises C# Exercises

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com