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

时间:2011-08-10 13:27:46

标签: c# string 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");

我想返回6个字母的所有单词,以字母“a”开头,并且“t”作为第5个字母,结果应该返回单词“abbots”和“abnats”。

var result = from w in words
             where w.StartsWith("a") && //where ????

我需要添加什么条款来满足第5个字母的't'要求?

5 个答案:

答案 0 :(得分:7)

var result = from w in words
             where w.Length == 6 && w.StartsWith("a") && w[4] == 't'
             select w;

答案 1 :(得分:1)

您可以使用索引器:

where w.StartsWith("a") && w.Length > 5 && w[4] == 't' 

如果没有Length检查,这将为较小的单词抛出异常。

请记住,索引器是从零开始的。

答案 2 :(得分:1)

// Now return all words of 6 letters that begin with letter "a" and has "t" as
// the 5th letter. The result should return the words "abbots" and "abnats".

var result = words.Where(w => 
    // begin with letter 'a'
    w.StartsWith("a") &&
    // words of 6 letters
    (w.Length == 6) &&
    // 't' as the 5th letter
    w[4].Equals('t'));

答案 3 :(得分:1)

我测试了以下代码,它给出了正确的结果:

var result = from w in words
             where w.StartsWith("a") && w.Length == 6 && w.Substring(4, 1) == "t"
             select w;

答案 4 :(得分:1)

在回答修改后的问题时,如果要查看最后两个字母,可以使用EndWith方法或指定要检查的索引。正如SLaks指出的那样,如果你使用索引,那么你还必须检查长度,以确保较小的单词不会导致问题。

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

var result1 = from word in words
              where word.Length == 6 && word.StartsWith("a") && word.EndsWith("ts")
              select word;

var result2 = from word in words
              where word.Length == 6 && word.StartsWith("a") && word[4] == 't' && word[5] == 's'
              select word;
相关问题