Check If String Contains All “?”

前端 未结 8 1199
离开以前
离开以前 2021-01-17 11:35

How can I check if a string contains all question marks? Like this:

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

相关标签:
8条回答
  • 2021-01-17 12:04
    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.

    0 讨论(0)
  • 2021-01-17 12:07
            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

    0 讨论(0)
  • 2021-01-17 12:11

    You can use Enumerable.All:

    bool isAllQuestion = input.All(c => c=='?');
    
    0 讨论(0)
  • 2021-01-17 12:13

    you could do it in linq...

    bool result = input.ToCharArray().All(c => c=='?');
    
    0 讨论(0)
  • 2021-01-17 12:16

    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;
        }
    
    0 讨论(0)
  • 2021-01-17 12:17
    var isAllQuestionMarks = input.All(c => c == '?');
    
    0 讨论(0)
提交回复
热议问题