How to know if the first character of a string is capitalized?

Asked

Viewed 567 times

2

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

How to do?

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();
        }

4 answers

4


One string is a collection of characters. Then you should take the first and use the method IsUpper() to return if it is uppercase. To avoid negation could use if it is lowercase with IsLower(), thus: char.IsLower(king[0]). In some cases it may be more interesting the option with culture invariance (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");    
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

It wouldn’t look like this:

char.IsUpper(king[i][0])
  • Yours is not working

  • I believe you did something wrong so I put link in the answer showing that it works. The only thing I had wrong is that I needed to reverse the condition and give the output.

  • Dei Ctrl c, Ctrl v in my project, it is not validating the first capital letter

  • 2

    I think you need to analyze what you are doing. Programming is not copying and pasting, it is understanding what is happening with the code. I put in two different fonts showing that it works. Obviously I had to change the code to be able to compile, after all you did not put all the code, if you had put all of it I could help more. I can’t rewrite all your code, because I would have to guess what it is, so I can put something that you can paste and compile without changes.

1

A simple way to check whether the first character is capitalized (or not) is:

char.IsUpper(kings[0])

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.

0

I didn’t test that code but it might help you

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.