How do I know if the first character of a string is uppercase?

2

I need to know if the first character of a string is uppercase and does not let the program follow.

How to do it?

Console.Write("Digite o nome do " + i + "º rei: " );
            kings[i] = Console.ReadLine();

        while ((kings[i].Length < 1 ||  kings[i].Length > 20 ) )
        {
            Console.WriteLine("O nome está inválido");
            Console.Write("Digite novamente");
            kings[i] = Console.ReadLine();
        }
    
asked by anonymous 10.10.2018 / 21:20

4 answers

4

A string is a collection of characters. Then you should get the first one and use the IsUpper() to return if uppercase. To avoid denial you could use it if it is minuscule with IsLower() , like: char.IsLower(king[0]) . In some cases the option with culture invariance may be more interesting ( ToUpperInvariant() ).

using static System.Console;

public class Program {
    public static void Main() {
        Write("Digite o nome do rei: " );
        while (true) {
            var king = ReadLine();
            if (king.Length > 0 && king.Length < 21 && char.IsUpper(king[0])) break;
            WriteLine("O nome está inválido\nDigite novamente");    
        }
    }
}

See running on .NET Fiddle . And in Coding Ground . Also put it in GitHub for future reference .

It would not look like this:

char.IsUpper(king[i][0])
    
10.10.2018 / 21:25
1

A simple way to check if the first character is uppercase (or not) is:

char.IsUpper(kings[0])
    
10.10.2018 / 21:32
0

You can create a Boolean variable that tells you if the first character is uppercase, and make your IF with it.

bool estaMaisculo = "Teste".ToCharArray()[0].ToString() == "Teste".ToCharArray()[0].ToString().ToUpper();

Instead of "test", you can put your variable.

    
10.10.2018 / 21:26
0

I have not tested this code but it might help you.

kings[0].CompareTo(kings[0].ToString().ToUpper());

    
10.10.2018 / 21:27