user2179026 user2179026 - 2 months ago 7
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!!!


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;