Home > front end >  Count how many times a "name" and "surname" is in a text in c# visual studio
Count how many times a "name" and "surname" is in a text in c# visual studio

Time:10-24

I want to be able to count a name and surname in C# with visual studio. Currently I can only search for 1 word in the text. I'm creating console applications using .NET 5.0 (current).

(When the input is "Harry" it counts how many times Harry has been found, when the input is "Harry Potter" it always counts as 0 even when there are multiple occurrences of "Harry Potter" in the text.)

Ive been looking for answers on google but can only find how to do count 1 word.

Here's my current code:

using System;
using System.IO;

namespace Harry
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            StreamReader stream = File.OpenText("Harry Potter and the Sorcerer.txt");
            string text = stream.ReadToEnd();

            string woord = "";
            int count = 0;

            foreach (var item in text)
            {
                if (Char.IsLetter(item))
                {
                    woord = woord   item;
                }
                else
                {
                    if(woord == input)
                    {
                        count  ; 
                    }
                    woord = "";
                }
            }
            Console.Write(input   ": "   count   " occurrences");
        }
    }
}

CodePudding user response:

Perhaps, in line with Auditive's suggestion:

int count = System.Text.RegularExpressions.Regex.Matches(text, input, RegexOptions.IgnoreCase).Count

If you're still short, change input so it has the value harry\s potter, the \s meaning "at least one whitespace", just in case your text has harrySPACESPACEpotter.. (and welcome to the wonderful, arcane world of regular expressions)

And if you're still short I think you might have a spelling error in the document!

  •  Tags:  
  • c#
  • Related