[英]Check If String Contains All “?”
如何檢查字符串是否包含所有問號? 像這樣:
string input =“????????”;
你可以使用Enumerable.All :
bool isAllQuestion = input.All(c => c=='?');
var isAllQuestionMarks = input.All(c => c == '?');
string = "????????";
bool allQuestionMarks = input == new string('?', input.Length);
剛剛進行了比較:
這種方式是比輸入快的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();
}
弦方式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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.