开发者

How to return all words that begin and end in certain characters?

开发者 https://www.devze.com 2023-03-27 06:34 出处:网络
Sorry.. I have asked a very similar question earlier.. However this time i want to retrieve all words that end in certain characters

Sorry.. I have asked a very similar question earlier.. However this time i want to retrieve all words that end in certain characters

I have a 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("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.Leng开发者_Go百科th == 6 && w.StartsWith("a") && //????


I haven't compiled and tested this, but it should work.

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


Use EndsWith to check for characters at the end.

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

Use IndexOf to check for words starting at certain position (in your case starting at 5th):

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


Just use .EndsWith() for suffixes.

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


A Regex is your friend here:

Regex regEx = new Regex("^a[A-Za-z]*ts$");
var results = from w in words where regEx.Match(w).Success select w;

Also note than when using LINQ's query comprehension syntax, you'll need a select at the end of it (even if it's just the original from variable.)


You can try a bit of regex if you feel up to it:

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;

This should match anything starting with 'a' and ending with 'a'.


You be able to use the EndsWith() function:

Usage:

var test=   FROM w in words
           WHERE w.Length == 6
              && w.StartsWith("a")
              && w.EndsWith("ts");

Alterative:

var test = words.Where(w =>w.Length==6 && w.StartsWith("a") && w.EndsWith("ts"));
0

精彩评论

暂无评论...
验证码 换一张
取 消