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

173 views Asked by At

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.");

                }

            }
2

There are 2 answers

0
Donut On

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}$");
5
JHBonarius On

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;
                    
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)
    {
        if (str.Length < 7) return false;
        var firstTwoIndex = 2;
        var lastFourIndex = str.Length - 4;
        for (var index = 0; index < str.Length; index++)
        {
            if (index < firstTwoIndex || index >= lastFourIndex)
            {
                if (!char.IsDigit(str[index])) return false;
            } else {
                if (!char.IsLetter(str[index])) return false;
            }
        }
        return true;
    }
}

returns

True
False

According to Benchmarkdotnet, the performance difference is:

|   Method |     Mean |    Error |   StdDev | Allocated |
|--------- |---------:|---------:|---------:|----------:|
|    RegEx | 90.72 ns | 0.983 ns | 0.871 ns |         - |
| Function | 12.57 ns | 0.236 ns | 0.330 ns |         - |

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