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

4
我有以下单词列表:

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

我想返回所有以字母"a"开头并且第五个字母为"t"的6个字母单词,结果应返回"abbots"和"abnats"这两个单词。

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

我需要添加哪个条件来满足第五个字母是“t”的要求?


谢谢您的回答。不过我想稍微修改一下我的问题,我想要返回所有第五个和第六个字母为“ts”的单词。 - Fraiser
5个回答

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

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

1
我已经测试了以下代码,并且它给出了正确的结果:
var result = from w in words
             where w.StartsWith("a") && w.Length == 6 && w.Substring(4, 1) == "t"
             select w;

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;

1
你可以使用索引器:
where w.StartsWith("a") && w.Length > 5 && w[4] == 't' 

没有 Length 检查,这将会对较小的单词抛出异常。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接