检查String是否包含全部"?"

Rob*_*ert 11 c#

如何检查字符串是否包含所有问号?像这样:

string input ="????????";

Ree*_*sey 21

你可以使用Enumerable.All:

bool isAllQuestion = input.All(c => c=='?');
Run Code Online (Sandbox Code Playgroud)


Jus*_*ner 16

var isAllQuestionMarks = input.All(c => c == '?');
Run Code Online (Sandbox Code Playgroud)


Pre*_*gha 6

        string = "????????";
        bool allQuestionMarks = input  == new string('?', input.Length);
Run Code Online (Sandbox Code Playgroud)

刚刚进行了比较:

这种方式比堆快x倍 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();
        }
Run Code Online (Sandbox Code Playgroud)

弦方式11 Linq方式4189