如何检查字符串是否仅包含“&”。我的意思是,如果用户将输入&或&&&&或字符串“&”。请注意,应该忽略http://myurl.com/&var=79或类似的内容。它应该检查那些包含&字符的字符串。请帮我!!!
我敢肯定正则表达式有更好的方法,但这是一个可能的解决方案:
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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句