检查字符串是否包含全部“?”
如何检查字符串是否包含所有问号? 像这样:
string input =“????????”;
var isAllQuestionMarks = input.All(c => c == '?');
你可以使用Enumerable.All :
bool isAllQuestion = input.All(c => c=='?');
string = "????????"; bool allQuestionMarks = input == new string('?', input.Length);
刚刚进行了比较:
这种方式是比输入快的堆input.All(c => c=='?');
public static void Main() { Stopwatch w = new Stopwatch(); string input = "????????"; w.Start(); bool allQuestionMarks; for (int i = 0; i < 10; ++i ) { allQuestionMarks = input == new string('?', input.Length); } w.Stop(); Console.WriteLine("String way {0}", w.ElapsedTicks); w.Reset(); w.Start(); for (int i = 0; i < 10; ++i) { allQuestionMarks = input.All(c => c=='?'); } Console.WriteLine(" Linq way {0}", w.ElapsedTicks); Console.ReadKey(); }
弦方式11 Linq方式4189
这么多linq答案! 我们不能再用老式的方式做点什么吗? 这比linq解决方案快一个数量级。 更具可读性? 也许不是,但这就是方法名称的用途。
static bool IsAllQuestionMarks(String s) { for(int i = 0; i < s.Length; i++) if(s[i] != '?') return false; return true; }
bool allQuestionMarks = input.All(c => c == '?');
这使用LINQ All
方法 ,该方法 “确定序列的所有元素是否满足条件”。 在这种情况下,集合的元素是字符,条件是字符等于问号字符。
不太可读…但正则表达式是另一种方法(它很快):
// Looking for a string composed only by one or more "?": bool allQuestionMarks = Regex.IsMatch(input, "^\?+$");
你可以在linq中做到这一点……
bool result = input.ToCharArray().All(c => c=='?');
你也可以试试这个:
private bool CheckIfStringContainsOnlyQuestionMark(string value) { return !value.Where(a => a != '?').Select(a => true).FirstOrDefault(); }