+ 3
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?
8 Answers
+ 10
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");
}
+ 5
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");
}
+ 3
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
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.
0
đ
đ
đ
°đ
š !!! So how it do? On code level
0
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..
0
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");
}
}
}
}
0
int noMatch = 0;
bool match = false;
while (count < words.Length)
{
if (words[count].Contains(letter))
{
Console.WriteLine(words[count]);
match = true;
}
else if (!words[count].Contains(letter))
{
noMatch++;
}
count++;
}
if(noMatch > 0 && match is false) { Console.WriteLine("No match"); }