How can I check if a string contains all question marks? Like this:
string input = \"????????\";
bool allQuestionMarks = input.All(c => c == '?');
This uses the LINQ All method, which "determines whether all elements of a sequence satisfy a condition." In this case, the elements of the collection are characters, and the condition is that the character is equal to the question mark character.
string = "????????";
bool allQuestionMarks = input == new string('?', input.Length);
Just ran a comparison:
this way is heaps x faster than the 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();
}
String way 11 Linq way 4189
You can use Enumerable.All:
bool isAllQuestion = input.All(c => c=='?');
you could do it in linq...
bool result = input.ToCharArray().All(c => c=='?');
So many linq answers! Can't we do anything the old-fashioned way any more? This is an order of magnitude faster than the linq solution. More readable? Maybe not, but that is what method names are for.
static bool IsAllQuestionMarks(String s) {
for(int i = 0; i < s.Length; i++)
if(s[i] != '?')
return false;
return true;
}
var isAllQuestionMarks = input.All(c => c == '?');