First, a letter is a slightly vague term: you mean a..z and a..z characters or a letter can belong to any alphabet, for example. .. and .. (Russian, Cyrillic letters). According to your current implementation, you need the second option.
A typical solution with a loop is to check before the first counter example:
Boolean validA = true; // true - no counter examples so far // Why for? foreach is much readble here foreach(Char ch in sname) // "!= '_'" is more readable than "Equals"; and wants no boxing if (!char.IsLetterOrDigit(ch) && ! (ch != '_')) { Boolean validA = false; // counter example (ie non-letter/digit symbol found) break; // <- do not forget this: there no use to check other characters }
However, you can simplify the code with Linq:
validA = sname.All(ch => Char.IsLetterOrDigit(ch) || ch == '_');
Or regex:
validA = Regex.IsMatch(sname, @"^\w*$");
Dmitry Bychenko
source share