如何返回以某些字符开头和结尾的所有单词?

时间:2011-08-10 14:55:23

标签: c# linq linq-to-objects

抱歉..我之前问了一个非常类似的问题..但是这次我要检索所有以某些字符结尾的单词

我有一个单词列表如下

        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") && //????

6 个答案:

答案 0 :(得分:2)

我没有编译和测试过这个,但它应该可以工作。

var result = from w in words
                     where w.Length == 6 && w.StartsWith("a") && w.EndsWith("ts")

答案 1 :(得分:1)

使用EndsWith检查最后的字符。

var result = from w in words
                     where w.Length == 6 && w.StartsWith("a") && w.EndsWith("ts")

使用IndexOf检查从 某个位置 开始的字词(在您的情况下从第5位开始):

  var result = from w in words
                     where w.Length == 6 && w.StartsWith("a") && (w.Length > 5 && w.IndexOf("ts", 4))

答案 2 :(得分:0)

只需使用.EndsWith()作为后缀。

var results = from w in words where w.Length == 6 
    && w.StartsWith("a") 
    && w.EndsWith("ts");

答案 3 :(得分:0)

您可以使用EndsWith()功能:

<强>用法:

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"));

答案 4 :(得分:0)

正则表达式是你的朋友:

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变量。)

答案 5 :(得分:0)

如果您愿意,可以尝试一下正则表达式:

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”结尾的任何内容。