user17595081
user17595081

Reputation: 13

Problem when calculating the sum of the positions of each letter of a string in the alphabet in C#

I have an issue with my code if I type in something like:

an apple

It will give me as output 33 instead of 65, which is the sum of the positions of each letter of that string in the alphabet: 65 = 1+14+1+16+16+12+5

How can I fix that?

static int alphaSum(string letter)
    {
        int sum = 0;
        char c = letter[0];
        for (int i = 0; i < letter.Length; i++)
        {
            c = (char)letter[i];
            sum += char.ToUpper(c) - 64;

        }

        return sum;
    }

Upvotes: 2

Views: 143

Answers (1)

Serge
Serge

Reputation: 43890

Your bug is that you are counting an empty space that gives you -32. You can use LINQ

var sum=letter.ToUpper().Where(l=> l>='A' &&  l<='Z').Select(l =>( (short)l)-64).Sum(); 

or fix your method

static int alphaSum(string letter)
{
    letter=letter.ToUpper();
    int sum = 0;
    for (int i = 0; i < letter.Length; i++)
    {
        var c = Convert.ToInt16(letter[i]);
        if( c < 65 || c > 90 ) continue;
        sum += c-64;
    }
    return sum;
}

sum

65

Upvotes: 1

Related Questions