开发者

Check If String Contains All "?"

How can I check if a string contains all qu开发者_如何学编程estion marks? Like this:

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


You can use Enumerable.All:

bool isAllQuestion = input.All(c => c=='?');


var isAllQuestionMarks = input.All(c => c == '?');


        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


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;
    }


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.


Not very readable... But a regular expression is another way to do it (and it's fast):

// Looking for a string composed only by one or more "?":
bool allQuestionMarks = Regex.IsMatch(input, "^\?+$");


you could do it in linq...

bool result = input.ToCharArray().All(c => c=='?');


You can also try this:

private bool CheckIfStringContainsOnlyQuestionMark(string value)
{
    return !value.Where(a => a != '?').Select(a => true).FirstOrDefault();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜