Roadmap › Coding Round Practice (DSA in C#) › Module: Foundations
Lessons in this course (14)

2. String programs

Basic★ Must knowLesson 2 of 14
csharp
// 1. Reverse a string (without Array.Reverse)
static string Reverse(string s)
{
    var chars = s.ToCharArray();
    for (int i = 0, j = chars.Length - 1; i < j; i++, j--)
        (chars[i], chars[j]) = (chars[j], chars[i]);
    return new string(chars);
}

// 2. Palindrome (ignore case and non-alphanumerics) — two pointers, O(n) time, O(1) space
static bool IsPalindrome(string s)
{
    int i = 0, j = s.Length - 1;
    while (i < j)
    {
        if (!char.IsLetterOrDigit(s[i])) { i++; continue; }
        if (!char.IsLetterOrDigit(s[j])) { j--; continue; }
        if (char.ToLowerInvariant(s[i]) != char.ToLowerInvariant(s[j])) return false;
        i++; j--;
    }
    return true;
}

// 3. Count each character
static Dictionary<char, int> CharCount(string s)
{
    var counts = new Dictionary<char, int>();
    foreach (var c in s) counts[c] = counts.GetValueOrDefault(c) + 1;
    return counts;
}

// 4. First non-repeating character
static char? FirstUnique(string s)
{
    var counts = CharCount(s);
    foreach (var c in s) if (counts[c] == 1) return c;
    return null;
}

// 5. Anagram check — O(n) with a count array for lowercase letters
static bool IsAnagram(string a, string b)
{
    if (a.Length != b.Length) return false;
    var count = new int[26];
    for (int i = 0; i < a.Length; i++) { count[a[i] - 'a']++; count[b[i] - 'a']--; }
    return count.All(c => c == 0);
}

// 6. Reverse words in a sentence
static string ReverseWords(string s) =>
    string.Join(' ', s.Split(' ', StringSplitOptions.RemoveEmptyEntries).Reverse());

// 7. Count vowels
static int Vowels(string s) => s.Count(c => "aeiouAEIOU".Contains(c));