How to return all words that begin and end with certain characters?
I have list of words as follows:
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("ac开发者_StackOverflowmatic");
I'd like to 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 = from w in words
where w.StartsWith("a") && //where ????
What clause do I need to add to meet the 5th letter is 't' requirement?
var result = from w in words
where w.Length == 6 && w.StartsWith("a") && w[4] == 't'
select w;
You can use the indexer:
where w.StartsWith("a") && w.Length > 5 && w[4] == 't'
Without the Length
check, this will throw an exception for smaller words.
Remember that the indexer is zero-based.
// 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'));
In answer to your revised question, if you want to check the last two letters, you can use the EndWith method or specify the indices you wish to check. As SLaks pointed out, if you use the indices, then you must also check the length to make sure smaller words don't cause a problem.
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;
I have tested the following code and it gave the right results:
var result = from w in words
where w.StartsWith("a") && w.Length == 6 && w.Substring(4, 1) == "t"
select w;
精彩评论