Home > Net >  How to use TryParse method for car license plate inquiry at C#
How to use TryParse method for car license plate inquiry at C#

Time:08-18

I want the first two and the last 4 characters to be numbers and the rest to remain as strings. If these conditions are not met, the license plate number should be obtained again.I couldn't go further than the code below.

        static string PlakaAl(string plaka)
        {
            int sayi;

            while (true)
            {
                Console.Write(plaka);
                string giris = Console.ReadLine();
                if (giris.Length == 8 && int.TryParse(giris.Substring(0, 2), out sayi) == true && int.TryParse(giris.Substring(4, 4), out sayi == true)

                {
                    return plaka;
                }

                else
                {
                    Console.WriteLine("Bu şekilde plaka girişi yapamazsınız. Tekrar deneyin.");

                }

            }

CodePudding user response:

This seems like it'd be a perfect opportunity to use a regular expression.

A regular expression is a pattern that the regular expression engine attempts to match in input text. A pattern consists of one or more character literals, operators, or constructs.

You can use this to define a pattern for the expected format of these license plates. This pattern ought to work for you based on your question:

^\d{2}[A-Z]{2}\d{4}$

Here's an explanation of what each part of this pattern will match:

  • ^ - the start of the string
  • \d{2} - two digits
  • [A-Z]{2} - two uppercase letters
  • \d{4} - four digits
  • $ - the end of the string

Note: I wasn't clear what you meant by "the rest to remain as strings". If you want to allow more than alphabetic characters, you'd just need to update the [A-Z] character group to include any other characters that are acceptable.

You can also see a visualization of this pattern here to help understand what it's doing.

You'd use it like this:

using System.Text.RegularExpressions;
...
var isValid = Regex.IsMatch(plaka, @"^\d{2}[A-Z]{2}\d{4}$");

CodePudding user response:

Usually RegEx is relatively slow (and objectively "easy" or "difficult" to read). You could also just test if the characters are digits (numbers) or letters:

using System;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var good = "12bafd3456";
        var bad = "1mns356";
        
        Console.WriteLine(Test(good));
        Console.WriteLine(Test(bad));
    }
    
    public static bool Test(string str) => 
        str.Length > 6 &&
        str[..2].All(c => Char.IsDigit(c)) &&
        str[2..^4].All(c => Char.IsLetter(c)) &&
        str[^4..].All(c => Char.IsDigit(c));
}

returns

True
False

(For if you don't know, The Range indexer value ^4 means: "four from the back")

edit: There's also a Char.IsUpper to test for an uppercase letter.

  • Related