DEV Community

Dat Ngo
Dat Ngo

Posted on • Edited on

How to Check if a String Contains Only Letters in C#

linq

public static bool IsOnlyLetters(string text)
{
    return text.All(char.IsLetter);
}
Enter fullscreen mode Exit fullscreen mode

regex

static bool IsOnlyLetters_Method2(string text)
{
    return Regex.IsMatch(text, @"^[\p{L}]+$");
}
Enter fullscreen mode Exit fullscreen mode

switch case

public static bool IsOnlyAsciiLettersBySwitchCase(string text)
{
    foreach (var item in text)
    {
        switch (item)
        {
            case >= 'A' and <= 'Z':
            case >= 'a' and <= 'z':
                continue;
            default:
                return false;
        }
    }
    return true;
}
Enter fullscreen mode Exit fullscreen mode

pattern matching

public static bool IsOnlyAsciiLettersByPatternMatching(string text)
{
    foreach (var item in text)
    {
        if (item is >= 'A' and <= 'Z' or >= 'a' and <= 'z')
            continue;
        else
            return false;
    }
    return true;
}
Enter fullscreen mode Exit fullscreen mode

Benchmark

public class StringLetterCheckBenchmark
    {
        private const string TestString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        private const string NonLetterString = "ABC123!@#";

        [Benchmark]
        public bool LinqMethod_OnlyLetters() => IsOnlyLetters(TestString);

        [Benchmark]
        public bool LinqMethod_WithNonLetters() => IsOnlyLetters(NonLetterString);

        [Benchmark]
        public bool RegexMethod_OnlyLetters() => IsOnlyLetters_Method2(TestString);

        [Benchmark]
        public bool RegexMethod_WithNonLetters() => IsOnlyLetters_Method2(NonLetterString);

        [Benchmark]
        public bool SwitchCaseMethod_OnlyLetters() => IsOnlyAsciiLettersBySwitchCase(TestString);

        [Benchmark]
        public bool SwitchCaseMethod_WithNonLetters() => IsOnlyAsciiLettersBySwitchCase(NonLetterString);

        [Benchmark]
        public bool PatternMatchingMethod_OnlyLetters() => IsOnlyAsciiLettersByPatternMatching(TestString);

        [Benchmark]
        public bool PatternMatchingMethod_WithNonLetters() => IsOnlyAsciiLettersByPatternMatching(NonLetterString);
}
Enter fullscreen mode Exit fullscreen mode
BenchmarkDotNet v0.13.12, macOS Ventura 13.3.1 (a) (22E772610a) [Darwin 22.4.0]
Apple M1, 1 CPU, 8 logical and 8 physical cores
.NET SDK 8.0.100
  [Host]     : .NET 8.0.0 (8.0.23.53103), Arm64 RyuJIT AdvSIMD
  DefaultJob : .NET 8.0.0 (8.0.23.53103), Arm64 RyuJIT AdvSIMD

| Method                               | Mean       | Error     | StdDev    |
|------------------------------------- |-----------:|----------:|----------:|
| LinqMethod_OnlyLetters               | 133.131 ns | 0.9107 ns | 0.8518 ns |
| LinqMethod_WithNonLetters            |  16.451 ns | 0.2000 ns | 0.1871 ns |
| RegexMethod_OnlyLetters              | 123.054 ns | 2.4522 ns | 3.0115 ns |
| RegexMethod_WithNonLetters           |  59.966 ns | 0.6924 ns | 0.5782 ns |
| SwitchCaseMethod_OnlyLetters         |  41.867 ns | 0.8452 ns | 1.0379 ns |
| SwitchCaseMethod_WithNonLetters      |   2.478 ns | 0.0179 ns | 0.0158 ns |
| PatternMatchingMethod_OnlyLetters    |  40.770 ns | 0.6179 ns | 0.4824 ns |
| PatternMatchingMethod_WithNonLetters |   2.447 ns | 0.0070 ns | 0.0058 ns |

Enter fullscreen mode Exit fullscreen mode

Conclusion

  • Best Performance: The SwitchCaseMethod and PatternMatchingMethod both show the best performance. The PatternMatchingMethod is slightly better overall if you are looking for the most efficient solution in both scenarios.
  • Worst Performance: The LinqMethod is the worst performer overall, especially for strings with only letters. The RegexMethod is also relatively slow, though slightly better than LINQ in some cases.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (2)

Collapse
 
peterpark88 profile image
PeterPark88

Which speed is better?

Collapse
 
dat_ngo_524c98f33bc09e368 profile image
Dat Ngo

Thank you for your feedback. Please check my updated post again; hopefully, it will be helpful

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay