How to check if any string contains alphanumeric characters in c#

Check whether any string contains alphanumeric characters or not in c# is quite simple. To achieve this there are so many logic and formulas are available online. I will explain how to achieve the above scenario without using the Regex function.

Below is the code which can be used to implement the above logic -

Step 1 -
// Function to Check for AlphaNumeric.
        public bool IsAlphaNumeric(String strToCheck)
        {
            bool tIsAlpha = false;
            bool tIsNumber = false;

            for (int i = 0; i < txtBox1.Text.Trim().Length; i++)
            {
                if (char.IsNumber(txtBox1.Text.Trim()[i]))
                {
                    tIsNumber = true;
                    break;
                }

                if (char.IsLetter(txtBox1.Text.Trim()[i]))
                {
                    tIsAlpha = true;
                    break;
                }
            }
            return (tIsAlpha && tIsNumber);
        }

Step 2 - Just call the above function in your C# code, pass the appropriate parameter and check the return value. If it returns true then string contains alphanumeric other wise doesn't alphanumeric characters.

Note - Above code might reduce the performance because it has to loop every time till the string length until there is no alphanumeric character.

Please share in comments if we can have other logic to achieve the same functionality.

Post a Comment

0 Comments