3 practice exercises for C# developer (beginner level)

1. Write a method that takes in an input string and returns true if all the characters in the string are unique and false if there is even a single repeated character.

public bool CheckAreCharactersUnique(string word)
{
    // Obviously unique
    if (word == null || word.Length <= 1) 
    {
        return true;
    }

    // Add all characters from word to new List, if char is already in List
    // return false immediately
    var chars = new List<char>();
    for (int i = 0; i < word.Length; ++i)
    {
        var c = word[i];

        if (chars.Contains(c))
        {
            return false;
        }

        chars.Add(c);
    }

    return true;
}

But there is easier and more realistic way to do this with LINQ:

public bool CheckAreCharactersUnique(string word)
{
    if (word == null || word.Length <= 1)
    {
        return true;
    }

    // Get all unique characters to new IEnumerable with Distinct method, 
    // compare with Length of word
    return word.Distinct().Count() == word.Length;
}

2. Given an array containing 9 numbers ranging from 0 to 9, write a method to find the missing number. Assume you have 9 numbers between 0 to 9 and only one number is missing. Note that numbers might have random order.

public int FindMissingNumber()
{
    var numbers = new List<int>() { 0, 3, 5, 4, 8, 6, 7, 1, 9};

    for (int i = 0; i < 10; i++)
    {
        if (!numbers.Contains(i))
        {
            return i;
        }
    }

    // -1 means there is no missing number
    return -1;
}

The other, trickier way, is to use LINQ (or calculate sum manually with loop) to deduct sum of given numbers from sum of numbers from 0 to 9, which is 45:

public int FindMissingNumber()
{
    var numbers = new List<int>() { 0, 3, 5, 4, 8, 6, 7, 1, 9};

    return 45 - numbers.Sum();
}

3. Write a method to replace all spaces in a string with a given replacement string. Don't use built-in Replace method of String class.

public string ReplaceWhiteSpaces(string text, string replaceWith)
{
    var resultText = "";

    foreach (var c in text)
    {
        if (c == ' ')
        {
            resultText += replaceWith;
        }
        else
        {
            resultText += c;
        }
    }

    return resultText;
}

Since String in .NET is immutable type, you might increase performance by using StringBuilder:

public string ReplaceWhiteSpaces(string text, string replaceWith)
{
    StringBuilder resultText = new StringBuilder();

    foreach (var c in text)
    {
        if (c == ' ')
        {
            resultText.Append(replaceWith);
        }
        else
        {
            resultText.Append(c);
        }
    }

    return resultText.ToString();
}

Similar articles

Comments