1

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();
        }
    }
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    [String.Contains Method](https://learn.microsoft.com/en-us/dotnet/api/system.string.contains?view=netframework-4.7.2) and [Enumerable.Where Method](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where?view=netframework-4.7.2) – TheGeneral Dec 11 '18 at 09:23

2 Answers2

6

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
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
  • 1
    I would be a good answer if you added the appropriate documentation and explain the answer a little so future readers learn something apposed to just a one line code answer – TheGeneral Dec 11 '18 at 09:25
  • Also `Where` is not going to return an `array` – TheGeneral Dec 11 '18 at 09:30
1

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
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215