C isalpha() The isalpha() function checks whether a character is an alphabet or not. In C programming, isalpha() function checks whether a character is an alphabet (a to z and A-Z) or not. If a character passed to isalpha() is an alphabet, it returns a non-zero integer, if not it returns 0.
We can use the regex ^[a-zA-Z]*$ to check a string for alphabets. This can be done using the matches() method of the String class, which tells whether the string matches the given regex.
Read the String. Convert all the characters in the given String to lower case using the toLower() method. Convert it into a character array using the toCharArray() method of the String class.
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_]+$");
bool result = input.All(Char.IsLetter);
bool result = input.All(Char.IsLetterOrDigit);
bool result = input.All(c=>Char.IsLetterOrDigit(c) || 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).
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;
}
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_]+$");
}
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.
Iterate through strings characters and use functions of 'Char' called 'IsLetter' and 'IsDigit'.
If you need something more specific - use Regex class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With