OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Letters In C#

Code snippet for how to Check If A String Contains Only Letters In C# with sample and detail explanation

When programming in C#, it frequently becomes necessary to check if a string contains only letters or not. Being able to verify the kind of characters present within a string can help prevent errors and enhance performance.

Code snippet for Checking If A String Contains Only Letters

To accomplish this in C#, one of the simplest ways is to use Regex. Here is a simple code snippet using Regex:

using System;
using System.Text.RegularExpressions;

class Program 
{
    static void Main()
    {
        // Test
        Console.WriteLine(IsStringOnlyLetters("HelloWorld"));  //Returns True
        Console.WriteLine(IsStringOnlyLetters("Hello123"));    //Returns False
    }

    static bool IsStringOnlyLetters(string input)
    {
        Regex reg = new Regex("[^a-zA-Z]");
        return !reg.IsMatch(input);
    }
}

Code Explanation for Checking If A String Contains Only Letters

Let’s go step by step in understanding this piece of code:

  1. First, we import the necessary namespaces like System and System.Text.RegularExpressions. The System.Text.RegularExpressions namespace contains Regex class that we are using for pattern matching.

  2. The IsStringOnlyLetters() method is created; the purpose of this method is to check whether the string input only contains letters or not. This method takes a string input and returns a boolean value (true if the string contains only letters and false otherwise).

  3. Inside the IsStringOnlyLetters() method, we initialized a reg Regex object with a pattern that matches any character that is not a letter.

  4. The IsMatch() method of the Regex class is called with inputstring provided as an argument; this method checks whether the input matches the pattern specified in the Regex object. If there is a match, it means that the input contains a character that is not a letter, hence return false; else, it will return true.

  5. In the Main() method, we attempt to check some strings to demonstrate the application of IsStringOnlyLetters() method. The Console’s WriteLine is used to print the result.

With this snippet, you can simply check if a string contains only letters in your C# programs. This simple validation algorithm can lead to more robust and bug-free software.

c-sharp