Languages
[Edit]
EN

C# / .NET - check if string contains only letters

0 points
Created by:
Zeeshan-Peel
850

In this article, we would like to show you how to check if string contains only letters in C#.

Quick solution:

string text1 = "ABC";
string text2 = "ABC123";

string regex = "^[a-zA-Z]+$";

bool result1 = Regex.IsMatch(text1, regex); // True
bool result2 = Regex.IsMatch(text2, regex); // False

or:

string text1 = "ABC";
string text2 = "ABC123";

bool result1 = text1.All(Char.IsLetter); // True
bool result2 = text2.All(Char.IsLetter); // False

 

1. Practical example using regex

In this example, we use a regular expression (regex) with IsMatch() to check if the strings contain only letters.

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string text1 = "ABC";
        string text2 = "ABC123";

        string regex = "^[a-zA-Z]+$";

        bool result1 = Regex.IsMatch(text1, regex);
        bool result2 = Regex.IsMatch(text2, regex);

        Console.WriteLine(result1); // True
        Console.WriteLine(result2); // False
    }
}

Output:

True
False

2. Using All() with IsLetter() method

In this example, we use All() from System.Linq with IsLetter() method to check if all characters in strings are letters.

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string text1 = "ABC";
        string text2 = "ABC123";

        bool result1 = text1.All(Char.IsLetter);
        bool result2 = text2.All(Char.IsLetter);

        Console.WriteLine(result1); // True
        Console.WriteLine(result2); // False
    }
}

Output:

True
False

References

  1. Regex.IsMatch Method (System.Text.RegularExpressions) | Microsoft Docs
  2. Enumerable.All<TSource>() Method (System.Linq) | Microsoft Docs
  3. Char.IsLetter Method (System) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join