id94 id94 - 2 months ago 21
C# Question

Convert characters of the string in alphabet integer position?

I want to calculate the character integer position of the string.
But when I run this method it calculates only the first char.

I must have output like this:

A = 1 + D = 4 + E = 5, => 10

private int letterNumber(string letter)
{
char c = letter[0];
for (int i = 0; i < letter.Length; i++)
{
c = (char)letter[i];
return char.ToUpper(c) - 64;
}
return c;
}

Answer

You return inside the loop - which is not your desired behaviour. With some minor refactoring, we can clean this up a bit:

private int letterNumber(string letter)
{
    int sum = 0;
    for (int i = 0; i < letter.Length; i++)
    {
        char c = letter[i]; // declare it in loop - you overwrite it here anyway
        sum += char.ToUpper(c) - 64;
    }
    return sum;
}
Comments