C# words with needed letters ? | Sololearn: Learn to code for FREE!


C# words with needed letters ?

https://code.sololearn.com/caV3vX3MMaQM/?ref=app We have a code. If the entered letter is in the word/words you need to output they, if not - output “No match”. This code do it, but if have/not letter - app output many times “no match” What is wrong?


3/28/2021 8:06:58 AM

Nazar Sumyk

7 Answers

New Answer


Nazar Sumyk Here is the solution int count = 0; foreach (string word in words) { if (word.Contains(letter)) { Console.WriteLine(word); count++; } } if(count == 0) { Console.WriteLine("No match"); }


Nazar Sumyk You printed matched word inside loop but didn't increase count. So increase count also inside if condition and outside the loop check if count is 0 then print "No match". For example: Inside the loop check: if (words[I].Contains(word)) { Console.WriteLine(word); count++; } Outside the loop check if (count == 0 ) { Console.WriteLine("No match"); }


Nazar Sumyk Don't print inside loop. Just increase count when string matched and check count outside the loop. So if count is greater than 0 then print Match otherwise print no match. Edited: Print no match if count is 0


The no match indicates that the word doesn't match the condition. If there are multiple words don't match, multiple no match will be outputed.


🅘🅜 🅰🅹 !!! So how it do? On code level


When you say a letter you mean a single letter? Becouse as it is written the code allow you to write a entire sentence...If yes I would change the type of the input to char (not string)...If not then you need to check each letter of the input..


If count remains 0 the loop never detected the letter while looping in the for each iterations. If the letter is found the word will be wrote to the console, & count increments therefore not writing “No match” to the console. string letter = Console.ReadLine(); int count = 0; foreach(var word in words) { if(word.Contains(letter)) { Console.WriteLine(word); count += 1; } } if(count == 0) { Console.WriteLine("No match"); } } } }