CSharp - Write program to Check Second Character


You will test the second character of the entered text.

A label has to have a capital X in the second position.


You need to test first whether the second character exists.

You access the second character using the Substring method that generally pulls a specific substring out of the given text.

The method requires two parameters.

  • The position of the first character. The position numbering starts with zero, so the second character position is 1.
  • The number of characters. In this case, what you need is just a single character, which is why the second parameter is 1, too.

You test first whether the text is at least two characters long.

if (label.Length >= 2 && label.Substring(1, 1) == "X") 

Its functioning relies upon the short-circuit evaluation of the && operator.

If the first condition of an AND join does not hold, the second one is not evaluated at all.

When the length of a label is less than 2, then the Substring call, which would fail, is skipped, and the program does not crash!


using System;
class Program/*from w w  w.  ja v  a 2s.c om*/
    static void Main(string[] args)
        // Input 
        Console.Write("Enter product label: ");
        string label = Console.ReadLine();
        // Evaluating 
        if (label.Length >= 2 && label.Substring(1, 1) == "X")
            Console.WriteLine("Label is OK");
            Console.WriteLine("Incorrect label");