user2179026 user2179026 - 1 year ago 85
ASP.NET (C#) Question

Check whether a string contain '&' character only

How to check whether a string contains "&" only. I mean that if user will enter & or &&& or a string of '&'. Please note that or something like this should be ignored. It should check for those string which contains & character. Please help me!!!

Answer Source

I'm sure there is a better way with regex but here is a possible solution:

class Program
        static void Main(string[] args)
            char testChar = '&';
            string test1 = "&";
            string test2 = "&&&&&&&&&&";
            string test3 = "&&&&&&&u&&&&&&&";

            Console.WriteLine(checkIfOnly(testChar, test1)); // true
            Console.WriteLine(checkIfOnly(testChar, test2)); // true
            Console.WriteLine(checkIfOnly(testChar, test3)); // false
            Console.WriteLine(checkIfOnly('u', test3));      // false
            Console.WriteLine(checkIfOnly('u', "u"));      // true
            Console.WriteLine(checkIfOnly('u', "uuuu"));      // true


        static bool checkIfOnly(char testChar, string s)
            foreach (char c in s)
                if (c != testChar) return false;
            return true;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download