This is my favorite way to see if a character is one of a set:
Function IsAlpha(chr As String)
If InStr(1, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", chr) <> 0 Then IsAlpha = True
End Function
First: completely trivial and meaningless nitpick: if you are going to specify the start argument as 1, just omit it entirely (1 is the default. (the OP requested VB6 so I assume that you are using it (the InStr Function should not be used in VB.NET), and if not, SHAME ON YOU for using the legacy functions in VB.NET!
).) Also, why not make the alphabetic string a constant? maybe even settle on the lower case or uppercase sequence only, and use LCase or UCase to change the case of the input before comparison?
IMO an IsAlpha() should mirror the functionality of the built in IsNumeric() Function- when you say IsNumeric("32") you get true, with your IsAlpha, IsAlpha("CB") returns False. Mine attempts to work with strings of any length, in a similar fashion to IsNumeric. Although to truly emulate it's function it should probably Trim() before the loop.
My version of a single-character IsAlpha function would be this:
Public Function IsAlpha(char as String) as Boolean
Dim ucaseasc as Integer
ucaseasc=Asc(Ucase$(char))
IsAlpha = (ucaseasc >=65 and ucaseasc <= 90)
End Function
And, because I have discovered that C# is superior in nearly every way to my old love VB6, this is the C# version:
private static bool IsAlpha(String alphastring)
{
return alphastring.ToUpper().All((w) => (w >= 65 && w <= 90));
}
Yep, a single line.
lambda expressions are awesome. The great thing is that in C#, and many other object oriented languages, a String is really just an array of Char objects, in this case, I am using the free extension methods provided on any IEnumerable<> Implementation. In this case, the "All()" extension method is acting on the IEnumerable<Char> that represents the string itself, then the lambda expression is executed for each character, where w is the iterating item. the All() function returns true if they all return true, and false otherwise. in this case, it's an extremely useful shorthand for what I would otherwise implement as a foreach, something like this:
private static bool IsAlpha(String alphastring)
{
foreach(char w in alphastring.ToUpper())
{
if (!(w >= 65 && w <= 90)) return false;
}
return true;
}
Which is a version of the original VB6 solution I gave, but that doesn't suck. (I clearly rushed through my original VB6 implementation, as I should be calling UCase$() only a single time before the loop, rather then for every single character. Oh well.