[英]How to return all words that begin and end in certain characters?
對不起..我之前問過一個非常相似的問題..但是這次我想檢索所有以某些字符結尾的單詞
我有一個單詞列表如下
List<string> words = new List<string>();
words.Add("abet");
words.Add("abbots"); //<---Return this
words.Add("abrupt");
words.Add("abduct");
words.Add("abnats"); //<--return this.
words.Add("acmatic");
//Now return all words of 6 letters that begin with letter "a" and has "ts" as the 5th and 6th letter
//the result should return the words "abbots" and "abnats"
var result = from w in words
where w.Length == 6 && w.StartsWith("a") && //????
我還沒有編譯和測試這個,但它應該可以工作。
var result = from w in words
where w.Length == 6 && w.StartsWith("a") && w.EndsWith("ts")
使用EndsWith
檢查末尾的字符。
var result = from w in words
where w.Length == 6 && w.StartsWith("a") && w.EndsWith("ts")
使用IndexOf
檢查以某些 position開頭的單詞(在您的情況下從第 5 個開始):
var result = from w in words
where w.Length == 6 && w.StartsWith("a") && (w.Length > 5 && w.IndexOf("ts", 4))
只需使用 .EndsWith() 作為后綴。
var results = from w in words where w.Length == 6
&& w.StartsWith("a")
&& w.EndsWith("ts");
您可以使用EndsWith()
function:
用法:
var test= FROM w in words
WHERE w.Length == 6
&& w.StartsWith("a")
&& w.EndsWith("ts");
替代品:
var test = words.Where(w =>w.Length==6 && w.StartsWith("a") && w.EndsWith("ts"));
正則表達式是您的朋友:
Regex regEx = new Regex("^a[A-Za-z]*ts$");
var results = from w in words where regEx.Match(w).Success select w;
另請注意,在使用 LINQ 的查詢理解語法時,您需要在其末尾添加一個select
(即使它只是from
變量的原始變量。)
如果您願意,可以嘗試一些正則表達式:
string pattern = @"^(a[a-zA-Z]*a)$";
var result = from w in words
where w.Length == 6 && System.Text.RegularExpressions.Regex.IsMatch(w, pattern) select w;
這應該匹配以“a”開頭並以“a”結尾的任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.