Search code examples
c#returntuplesrefout

How to have a function return both index and value of an array?


This function counts how often letter occur in a given string and puts that in an array (index is ascii-number of letter and value ist counted occurrences). Now I need to return both the letter (which it already does) and the value. Just by reading online I couldn't figure out how to use ref and alternatives to do that.

static char MostCommonLetter(string s)
    {
        int[] occurrances = new int[255];
        for (int i = 0; i < s.Length; i++)
        {
            if (char.IsLetter(s[i]))
            {
                int ascii = (int)s[i];
                occurrances[ascii]++;
            }
        }
        char maxValue = (char)Array.IndexOf(occurrances, occurrances.Max());
        return maxValue;
    }

Solution

  • In C# 7 and above, Value Tuples are your best bet. You could define your function as follows:

    static (char letter, int occurrences) MostCommonLetter(string s)
    {
        int[] occurrences = new int[255];
        for (int i = 0; i < s.Length; i++)
        {
            if (char.IsLetter(s[i]))
            {
                int ascii = (int)s[i];
                occurrances[ascii]++;
            }
        }
        char letter = (char)Array.IndexOf(occurrences, occurrences.Max());
        return (index: letter, occurrences: occurrences);
    }
    

    You could then reference the output like so:

    var (index, occurrences) = MostCommonLetter(yourString);