Re: How to make sure a string doesn't contain any integer??

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance




JLuv wrote:
well, i ended up using this...

private int isValid(ref string word)
{
int valid = 1;

if (String.Compare(word, "\0") != 0)
{
for (int i = 0; i < word.Length; i++)
{

if (!Char.IsLetterOrDigit(word[i]))
valid = -1;
}
}
return valid;
}

i found out that C# has a bunch of built in Char methods like
IsLetterOrDigit(), IsLetter(), IsDigit(), etc.
source: http://msdn2.microsoft.com/en-us/library/ms289266.aspx

I you don't mind some help cleaning up that code... I've added comments
to say why the changes:

// There's really no reason to return "int" here: you probably want
"bool"
// either true or false.
private bool IsValid(ref string word)
{
// Really no need to test for an empty string, either: for an empty
string
// execution will just skip the "for" loop. On top of which,
checking against
// a string containing a NUL control character is a C idiom, not
C#. If you really
// want to test for an empty string in C# you can test "if
(word.Length > 0)" or
// "if (word == "")"
foreach (char c in word)
{
if (!Char.IsLetterOrDigit(c))
{
// Some people are sticklers for there being only one
return point
// in a method, but whatever you do you don't want to keep
looping,
// testing characters after you know that the method will
return
// false.
return false;
}
}

// If the loop completes then the whole string is letters and
digits,
// or it's an empty string.
return true;
}

.



Relevant Pages