senzacionale
senzacionale

Reputation: 20936

Search inside an 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 an array of string? Is there any fast solution?

Thanks.

Upvotes: 4

Views: 1422

Answers (4)

prabhats.net
prabhats.net

Reputation: 444

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

    }

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245479

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

Upvotes: 3

Ian P
Ian P

Reputation: 12993

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.)

Upvotes: 0

SLaks
SLaks

Reputation: 888117

You can use LINQ:

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

If there was no match, this will return null.

Upvotes: 5

Related Questions