如何检查字符串是否仅包含"&".我的意思是,如果用户输入&或&&&或一串'&'.请注意,应忽略http://myurl.com/&var=79或类似的内容.它应检查包含&字符的字符串.请帮我!!!
fub*_*ubo 18
当你说
string仅包含"&"
我假设,具有任何其他字符的字符串无效.
string str = "&&&";
bool result = str.All(x => x == '&'); //true, because it contains no other char
另一种方式 - 没有linq的oneliner
bool result = str.Replace("&", String.Empty).Length == 0;
Bot*_*lan 15
我确信有一个更好的方法与正则表达式,但这是一个可能的解决方案:
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;
        }
    }
这是一个相当简单的方法:
bool allAmpersands = !string.IsNullOrEmpty(str) && str.Trim('&').Length == 0;
如果字符串不为空,它会在删除两端的&符号后检查字符串中是否还有任何内容.
使用RegEx解决方案
string str = "&&&&"; 
bool b = Regex.IsMatch(str,"^&+$");
| 归档时间: | 
 | 
| 查看次数: | 1184 次 | 
| 最近记录: |