Check string input content

How to check if my input is a specific string type. So there are no numbers, no "/", ...

+5
source share
5 answers

Well, to verify that the input is actually an object of type System.String, you can simply do:

bool IsString(object value)
{
    return value is string;
}

To make sure that a stringcontains only letters, you can do something like this:

bool IsAllAlphabetic(string value)
{
    foreach (char c in value)
    {
        if (!char.IsLetter(c))
            return false;
    }

    return true;
}

If you want to combine them, you can do this:

bool IsAlphabeticString(object value)
{
    string str = value as string;
    return str != null && IsAllAlphabetic(str);
}
+15
source

If you mean "string with letters completely", you can do:

string myString = "RandomStringOfLetters";
bool allLetters = myString.All( c => Char.IsLetter(c) );

This is based on the LINQ method and Char.IsLetter .

+10
source

, , , , . , , a-z A-Z, :

string s = "dasglakgsklg";
if (Regex.IsMatch(s, "^[a-z]+$", RegexOptions.IgnoreCase))
{
    Console.WriteLine("Only letters in a-z.");
}
else
{
    // Not only letters in a-z.
}

, , . , .

\p{L} [a-z] , , .

+6
using System.Linq;
...

bool onlyAlphas = s.All(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
+2

Something like this (not verified) might fit your (vague) requirement.

if (input is string)
{
    // test for legal characters?
    string pattern = "^[A-Za-z]+$";
    if (Regex.IsMatch(input, pattern))
    {
         // legal string? do something 
    }

    // or
    if (input.Any(c => !char.IsLetter(c)))
    {
         // NOT legal string 
    }
}
+1
source

All Articles