user10774914
user10774914

Reputation:

Finding all word with a specific letter in a string

I need to find out how to output all the word that contain "a". I have a string with all the months and want to output the ones that contain "a" to console. Here´s what i have so far

string[] Månedsdage = { 
  "Januar", "Februar", "Marts", 
  "April", "Maj", "Juni", 
  "juli", "August", "September", 
  "Oktober", "November", "December", 
  "Bichat" };

for (int i = 0; i < Månedsdage.Length; i++)
{
    for (int j = 0; j < Månedsdage[i].Length; j++)
    {
        if (Månedsdage[i].Substring(j,1) == "a")
        {
            Console.WriteLine("Alle måneder med A: ");
            Console.WriteLine(Månedsdage[j]);
            Console.ReadLine();
        }
    }
}

Upvotes: 1

Views: 1868

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186678

Unfortunately, Contains doesn't accept StringComparison, but IndexOf does: we can try filtering out these words where "a"th index is not negative (i.e. "a" appears in the word)

    string[] Månedsdage = { 
      "Januar", "Februar", "Marts", 
      "April", "Maj", "Juni", 
      "juli", "August", "September", 
      "Oktober", "November", "December", 
      "Bichat" };

    // StringComparison.CurrentCulture if you want case sensitive search
    var result = Månedsdage
      .Where(word => word.IndexOf("a", StringComparison.CurrentCultureIgnoreCase) >= 0);

    Console.Write(string.Join(Environment.NewLine, result));

Output:

Januar
Februar
Marts
April
Maj
August
Bichat

Upvotes: 1

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

What about this

string[] result = Månedsdage.Where(x=> x.ToLower().Contains('a')).ToArray();

.Contains() : To get all words containing letter a we used string method. This extension method checks whether a substring passed as a parameter is exist in given string or not.

Where() : To apply same condition on each element from string array, we used Linq extension method.

ToLower() : This method is used to make all characters of string in lower case. So it will not miss 'A' and 'a'. ToLower() will include April in resultant array. If you don't want April to be in your array, do not use ToLower()

POC: .net Fiddle

Output:

Januar
Februar
Marts
April  /*ToLower() ;)*/
Maj
August
Bichat

Upvotes: 6

Related Questions