I'm pretty new to C# however I am trying to solve this question down below. Any way I can count that specific word each time even when its repeated twice in the same list element? I am trying to not use the Split() function. Thanks for the help
string wordToSearch = "Pig";
List<string> sentences = new List<string>()
{
"The animal I really dig,",
"Above all others is the pig.",
"Pigs are noble. Pigs are clever,",
"Pigs are courteous. However,",
"Now and then, to break this rule,",
"One meets a pig who is a fool.",
"What, for example, would you say,",
"If strolling through the woods one day,",
"Right there in front of you you saw",
"A pig who'd built his house of STRAW?",
"The Wolf who saw it licked his lips,",
"And said, 'That pig has had his chips.'",
"'Little pig, little pig, let me come in!'",
"'No, no, by the hairs on my chinny-chin-chin!'",
"'Then I'll huff and I'll puff and I'll blow your house in!'"
};
foreach (string sentence in sentences)
{
int count = 0;
if (sentence.ToUpper().Contains(wordToSearch.ToUpper()))
{
count ;
Console.WriteLine(sentence " " "[" count "]");
}
else
{
Console.WriteLine(sentence " " "[" count "]");
}
}
CodePudding user response:
You'll probably want to call IndexOf
in a loop, until there are no more matches found:
static int CountRepeats(
string source,
string toFind,
StringComparison comparison = StringComparison.OrdinalIgnoreCase)
{
int result = 0;
int index = source.IndexOf(toFind, comparison);
while (index != -1)
{
result ;
// Resume the search just after the end of the previous occurrence:
index = source.IndexOf(toFind, index toFind.Length, comparison);
}
return result;
}
NB: As with your current code, this will find matches within other words. For example, it will find the pig
in spiggot
. That may or may not be correct, depending on the precise requirements.
If you want the total count across all sentences, you'll need to move your count
variable outside of your loop:
int count = 0;
foreach (string sentence in sentences)
{
int sentenceCount = CountRepeats(sentence, wordToSearch);
Console.WriteLine("{0} [{1}]", sentence, sentenceCount);
count = sentenceCount;
}
Console.WriteLine("Total count: {0}", count);
CodePudding user response:
Try this:
foreach (string sentence in sentences)
{
int count = 0;
if (sentence.ToUpper().Contains(wordToSearch.ToUpper()))
{
string[] words = sentence.ToUpper().Replace(",", "").Replace(".", "").Split(Convert.ToChar(" "));
Console.WriteLine(sentence " " "[" words.Where(s => s.Equals(wordToSearch.ToUpper())).Count().ToString() "]");
}
else
{
Console.WriteLine(sentence " " "[" count "]");
}
}