0

Basically I'm just trying to check if a user input is all uppercase or lowercase. Currently my problems are that the code returns true1 or true2 every iteration and if the input is all uppercase the first for loop breaks into the next loop which- since none of the letters are lowercase - returns false. Sorry if this problem is formatted incorrectly, I'm quite new.


namespace CheckifSameCase
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize user input as var "input".
            string str = Console.ReadLine();
            char[] characters = str.ToCharArray();

            //This for loop iterates through the user input and checks if all letters are uppercase.
            //if not all letters are uppercase then the loop breaks to the next loop.
            for (int i = 0; i < characters.Length; i++)
            {
                if (char.IsUpper(characters[i]))
                {
                    Console.WriteLine("True1");
                }
                else
                {
                    break;
                }
            }

            //This for loop checks for lowcase letters and returns false if all letters aren't lowercase.
            for (int i = 0; i < characters.Length; i++)
            {
                if (char.IsLower(characters[i]))
                {
                    Console.WriteLine("True2");
                }
                else
                {
                    Console.WriteLine("False");
                    break;
                }
            }

        }
    }
}
Dex
  • 11
  • @oliverr they want to detect if its all caps, all lowercase, or mixed so this does not really answer their question. It seems like they understand how to detect all caps based on their code – Owen Kuhn Aug 15 '21 at 22:58
  • @OwenKuhn `str.All(c => char.IsUpper/IsLower(c))` and `str.All(c => char.IsLower(c))` do [the job](https://stackoverflow.com/a/448267/12031933). Of course an optimized handmade loop to flag/unflag allLower and allUpper to break will do too without parsing twice the string if we need such a thing... I have not the time to write it. Did I misunderstand the question? –  Aug 15 '21 at 23:01

1 Answers1

0

I don't know C# but here is one way of doing it. Just check the first character if its uppercase all others should be uppercase or it prints false. If the first character is lowercase all others should be lowercase or it prints false. Then if you reach the end of the program (without returning) you can see if it was all uppercase or all lowercase and print accordingly.

bool isUpper = char.isUpper(characters[0]);
for(int i = 0; i < characters.Length; i++) {
    if(isUpper != char.isUpper(characters[i])) {
        Console.WriteLine("False");
        return;
    }
}
if(isUpper) {Console.WriteLine("True1");}
else {Console.WriteLine("True2");}
Owen Kuhn
  • 85
  • 6