简体   繁体   中英

search inside array of strings

string[] words = {"januar", "februar", "marec", "april", "maj", "junij", "julij",    
"avgust", "september", "oktober", "november", "december"};

i have word "ja" for example or "dec". How can i get "januar" or "december" from array of string? Is any fast solution?

Thx

You can use LINQ:

words.FirstOrDefault(w => w.StartsWith(str, StringComparison.OrdinalIgnoreCase))

If there was no match, this will return null .

If you're using the newer versions of C# (3.0 and up) you can use LINQ:

// to find a match anywhere in the word
words.Where(w => w.IndexOf(str, 
    StringComparison.InvariantCultureIgnoreCase) >= 0);

// to find a match at the beginning only
words.Where(w => w.StartsWith(str, 
    StringComparison.InvariantCultureIgnoreCase));
List<string> words = new List<string>() { "January", "February", "March", "April" };

var result = words.Where(w => w.StartsWith("jan", StringComparison.OrdinalIgnoreCase));

Will find the results that start with whatever criteria you provide, and ignore the case (optional.)

You can Use simple Regular Expressions as well... string[] words = { "januar", "februar", "marec", "april", "maj", "junij", "julij", "avgust", "september","oktober", "november", "december" };

    string sPattern = "ja";

    foreach (string s in words)
    {


        if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
        {
            System.Console.WriteLine("  (match for '{0}' found)", sPattern);
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM