R. Jacobs - 5 days ago 5
C# Question

# C# Counting the number of upper and lower case letters in a string

Hi I've been asked to do a task which calculates the number of vowels, consonants, upper and lower case letters in a string.

I'm having trouble working out upper and lower case letters in a string.
I can successfully count the number of vowels and constants but upper and lower case letters seems to be a pain.

Here's the code:

``````    public void Calculate()
{
foreach(string sentence in sentenceList)
{
sentences++;

for (int i = 0; i < sentence.Length; i++)
{
if (vowelsArray.Contains(sentence[i]))
{
vowels++;
}
else if (consonantsArray.Contains(sentence[i]))
{
consonants++;
}
else if (char.IsUpper(sentence[i]))
{
upperCaseLetters++;
}
else if (char.IsLower(sentence[i]))
{
lowerCaseLetters++;
}
}
}
}
``````

The value for the upper and lower case letters is 0. (It shouldn't be)

Any suggestions? Thanks!

You have a chain of `if`/`else` statements and the first condition that is matched (either the vowels or consonants) will prevent any future conditions from being matched. Break the `if`/`else` chain into 2 chains:

• Vowels vs Consonants
• Uppercase vs Lowercase

See updated code below:

``````    public void Calculate()
{
foreach(string sentence in sentenceList)
{
sentences++;

for (int i = 0; i < sentence.Length; i++)
{
if (vowelsArray.Contains(sentence[i]))
{
vowels++;
}
else if (consonantsArray.Contains(sentence[i]))
{
consonants++;
}

// the else was removed here!
if (char.IsUpper(sentence[i]))
{
upperCaseLetters++;
}
else if (char.IsLower(sentence[i]))
{
lowerCaseLetters++;
}
}
}
}
``````