Verifying that a string contains only letters in C#

C#String

C# Problem Overview


I have an input string and I want to verify that it contains:

  • Only letters or
  • Only letters and numbers or
  • Only letters, numbers or underscore

To clarify, I have 3 different cases in the code, each calling for different validation. What's the simplest way to achieve this in C#?

C# Solutions


Solution 1 - C#

Only letters:

Regex.IsMatch(input, @"^[a-zA-Z]+$");

Only letters and numbers:

Regex.IsMatch(input, @"^[a-zA-Z0-9]+$");

Only letters, numbers and underscore:

Regex.IsMatch(input, @"^[a-zA-Z0-9_]+$");

Solution 2 - C#

bool result = input.All(Char.IsLetter);

bool result = input.All(Char.IsLetterOrDigit);

bool result = input.All(c=>Char.IsLetterOrDigit(c) || c=='_');

Solution 3 - C#

Letters only:

Regex.IsMatch(theString, @"^[\p{L}]+$");

Letters and numbers:

Regex.IsMatch(theString, @"^[\p{L}\p{N}]+$");

Letters, numbers and underscore:

Regex.IsMatch(theString, @"^[\w]+$");

Note, these patterns also match international characters (as opposed to using the a-z construct).

Solution 4 - C#

For those of you who would rather not go with Regex and are on the .NET 2.0 Framework (AKA no LINQ):

Only Letters:

public static bool IsAllLetters(string s)
{
    foreach (char c in s)
    {
        if (!Char.IsLetter(c))
            return false;
    }
    return true;
}

Only Numbers:

    public static bool IsAllDigits(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsDigit(c))
                return false;
        }
        return true;
    }

Only Numbers Or Letters:

    public static bool IsAllLettersOrDigits(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsLetterOrDigit(c))
                return false;
        }
        return true;
    }

Only Numbers Or Letters Or Underscores:

    public static bool IsAllLettersOrDigitsOrUnderscores(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsLetterOrDigit(c) && c != '_')
                return false;
        }
        return true;
    }

Solution 5 - C#

I think is a good case to use Regular Expressions:

public bool IsAlpha(string input)
{
	return Regex.IsMatch(input, "^[a-zA-Z]+$");
}

public bool IsAlphaNumeric(string input)
{
	return Regex.IsMatch(input, "^[a-zA-Z0-9]+$");
}

public bool IsAlphaNumericWithUnderscore(string input)
{
	return Regex.IsMatch(input, "^[a-zA-Z0-9_]+$");
}

Solution 6 - C#

You can loop on the chars of string and check using the Char Method IsLetter but you can also do a trick using String method IndexOfAny to search other charaters that are not suppose to be in the string.

Solution 7 - C#

Iterate through strings characters and use functions of 'Char' called 'IsLetter' and 'IsDigit'.

If you need something more specific - use Regex class.

Solution 8 - C#

If You are a newbie then you can take reference from my code .. what i did was to put on a check so that i could only get the Alphabets and white spaces! You can Repeat the for loop after the second if statement to validate the string again

       bool check = false;

       Console.WriteLine("Please Enter the Name");
       name=Console.ReadLine();

       for (int i = 0; i < name.Length; i++)
       {
           if (name[i]>='a' && name[i]<='z' || name[i]==' ')
           {
               check = true;
           }
           else
           {
               check = false;
               break;
           }

       }

       if (check==false)
       {
           Console.WriteLine("Enter Valid Value");
           name = Console.ReadLine();
       }

Solution 9 - C#

I haven't yet seen a solution using pattern matching:

public static bool ContainsOnlyLetters(this string input)
{
	bool isValid = true;

	for (int i = 0; isValid && i < input.Length; i++)
	{
		isValid &= input[i] is > 'A' and < 'Z' or > 'a' and < 'z';
	}

	return isValid;
}

or if you really really hate readable code:

public static bool ContainsOnlyLetters(this string input)
{
	bool isValid = true;
	for (int i = 0; i < input.Length && (isValid &= input[i] is > 'A' and < 'Z' or > 'a' and < 'z'); i++);
	return isValid;
}

Solution 10 - C#

Recently, I made performance improvements for a function that checks letters in a string with the help of this page.

I figured out that the Solutions with regex are 30 times slower than the ones with the Char.IsLetterOrDigit check.

We were not sure that those Letters or Digits include and we were in need of only Latin characters so implemented our function based on the decompiled version of Char.IsLetterOrDigit function.

Here is our solution:

internal static bool CheckAllowedChars(char uc)
    {
        switch (uc)
        {
            case '-':
            case '.':
            case 'A':
            case 'B':
            case 'C':
            case 'D':
            case 'E':
            case 'F':
            case 'G':
            case 'H':
            case 'I':
            case 'J':
            case 'K':
            case 'L':
            case 'M':
            case 'N':
            case 'O':
            case 'P':
            case 'Q':
            case 'R':
            case 'S':
            case 'T':
            case 'U':
            case 'V':
            case 'W':
            case 'X':
            case 'Y':
            case 'Z':
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                return true;
            default:
                return false;
        }
    }

And the usage is like this:

 if( logicalId.All(c => CheckAllowedChars(c)))
 { // Do your stuff here.. }

Solution 11 - C#

Please find the method to validate if char is letter, number or space, otherwise attach underscore (Be free to modified according your needs)

public String CleanStringToLettersNumbers(String data)
{
    var result = String.Empty;

    foreach (var item in data)
    {
        var c = '_';

        if ((int)item >= 97 && (int)item <= 122 ||
            (int)item >= 65 && (int)item <= 90 ||
            (int)item >= 48 && (int)item <= 57 ||
            (int)item == 32)
        {
            c = item;
        }

        result = result + c;
    }

    return result;
}

Solution 12 - C#

Use this to scan each CHARACTER of the STRING.

You can add SWITCH STATEMENT after 1 IF STATEMENT if you want to include "many" characters aside from 'SPACE'.

string myInput = string.Empty;
bool check = false; 

// Loops the input module
while (check is false)
{
	Console.WriteLine("Enter Letters Only");
	myInput = Console.ReadLine();

	// Loops the SCANNING PROCCESS of each character of the string
	for (int i = 0; i < myInput.Length; i++)                  
	{
		// Prints current scanning proccess 1 by 1(character by character) inside the string
		Console.WriteLine("Checking Character \"{0}\" ",myInput[i]);
		
		// Letters only		
		if (Char.IsLetter(myInput[i]))
		{
			check = true;
		}
		
		// Includes "SPACE" character
		else if (myInput[i] == ' ')
		{
			check = true;
		}
		else
		{
			check = false;
			Console.WriteLine("wrong input. \"{0}\" is not a string", myInput[e]);
			Console.WriteLine("pls try again");
			// Exits from loop of scanning proccess due to unwanted input
			break;        
		}  
	}
	// Ends SCANNING of 1 CHARACTER inside the string
} 
Console.WriteLine("Input Approved: \"{0}\"", myInput);
Console.WriteLine("Press any key to exit");
Console.ReadKey();

OUTPUT: With FALSE Input >Enter Letters Only
Agent 47
Checking Character "A"
Checking Character "g"
Checking Character "e"
Checking Character "n"
Checking Character "t"
Checking Character " "
Checking Character "4"
Oops. "4" is not a Valid Input
pls try again

Enter Letters Only

OUTPUT: Without FALSE Input >Enter Letters Only
Agent Forty Seven
Checking Character "A"
Checking Character "g"
Checking Character "e"
Checking Character "n"
Checking Character "t"
Checking Character " "
Checking Character "F"
Checking Character "o"
Checking Character "r"
Checking Character "t"
Checking Character "y"
Checking Character " "
Checking Character "S"
Checking Character "e"
Checking Character "v"
Checking Character "e"
Checking Character "n"
Input Approved: "Agent Forty Seven"
Press any key to exit

Or SWITCH STATEMENT only, if you only want to include "some" CHARACTERS from LETTER category & "some" CHARATERS from DIGIT category.

switch (myInput[e])
{ 
	case 'a':
	case 'b':
	case 'c':
	case 'd': 
	case '1':
	case '2':
	case '3':
	case '!':
	case '@': 
	case '#':  
		check = true;
		break; 
	default:
		check = false;
		Console.WriteLine("Oops, \"{0}\" is not a string", myInput[i]);
		Console.WriteLine("pls try again\n");
		break;
}
if (check == false) break ;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBab YogooView Question on Stackoverflow
Solution 1 - C#Philippe LeybaertView Answer on Stackoverflow
Solution 2 - C#Muhammad Hasan KhanView Answer on Stackoverflow
Solution 3 - C#Fredrik MörkView Answer on Stackoverflow
Solution 4 - C#GaffView Answer on Stackoverflow
Solution 5 - C#Christian C. SalvadóView Answer on Stackoverflow
Solution 6 - C#BagetView Answer on Stackoverflow
Solution 7 - C#Arnis LapsaView Answer on Stackoverflow
Solution 8 - C#Khyzar Ishaq KapoorView Answer on Stackoverflow
Solution 9 - C#Frederik HoeftView Answer on Stackoverflow
Solution 10 - C#Aytaç Utku TOPALView Answer on Stackoverflow
Solution 11 - C#Alfred RojasView Answer on Stackoverflow
Solution 12 - C#Mohammad D. AliView Answer on Stackoverflow