check alphanumeric characters in string in c#

后端 未结 8 1087
轻奢々
轻奢々 2020-12-15 05:04

I have used the following code but it is returning false though it should return true

string check,zipcode;
zipcode=\"10001 New York, NY\";
check=isalpha         


        
8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 05:55

    If you want a non-regex ASCII A-z 0-9 check, you cannot use char.IsLetterOrDigit() as that includes other Unicode characters.

    What you can do is check the character code ranges.

    • 48 -> 57 are numerics
    • 65 -> 90 are capital letters
    • 97 -> 122 are lower case letters

    The following is a bit more verbose, but it's for ease of understanding rather than for code golf.

        public static bool IsAsciiAlphaNumeric(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }
    
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] < 48) // Numeric are 48 -> 57
                {
                    return false;
                }
    
                if (str[i] > 57 && str[i] < 65) // Capitals are 65 -> 90
                {
                    return false;
                }
    
                if (str[i] > 90 && str[i] < 97) // Lowers are 97 -> 122
                {
                    return false;
                }
    
                if (str[i] > 122)
                {
                    return false;
                }
            }
    
            return true;
        }
    

提交回复
热议问题