简体   繁体   中英

C# Search for word in a text file and display the number of times it occurs

I am struggling on how to finish up my application in Visual Studio, C#... Everything words as it should where it allows the user to open a text file and displays the text file in a listBox. The part of my application also has a textBox and searchButton so the user is able to search for a specific word in the text file and then there is an outputLabel which should display how many times the word (value inside textBox) occurs in the text file.

Below is the code for my searchButton and I am not sure where to go from here.

private void searchButton_Click(object sender, EventArgs e)
        {
            int totalAmount;
            totalAmount = AllWords.Count();
        }

If it is helpful to you to help me, her is the rest of my code for the application ( "using System.IO;" is also in my code, by the way )

namespace P6_File_Reader
{
    public partial class ReadingFiles : Form
    {
        public ReadingFiles()
        {
            InitializeComponent();
        }

        List<string> AllWords = new List<string>();

        private void openButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog NewDialogBox = new OpenFileDialog();

            // will open open file dialog in the same folder as .exe
            NewDialogBox.InitialDirectory = Application.StartupPath;

            // filter only .txt files
            NewDialogBox.Filter = "Text File | *. txt";
            if (NewDialogBox.ShowDialog() == DialogResult.OK)
            {
                // declare the variables
                string Line;
                string Title = "", Author = "";
                string[] Words;
                char[] Delimiters = { ' ', '.', '!', '?', '&', '(', ')',
                                              '-', ',', ':', '"', ';' };

                // declare the streamreader variable
                StreamReader inputfile;

                // to open the file and get the streamreader variable
                inputfile = File.OpenText(NewDialogBox.FileName);

                // to read the file contents
                int count = 0;

                while (!inputfile.EndOfStream)
                {
                    //count lines
                    count++;

                    // to save the title
                    Line = inputfile.ReadLine();
                    if (count == 1) Title = Line;

                    // to save the author
                    else if (count == 2) Author = Line;

                    // else
                    {
                        if (Line.Length > 0)
                        {
                            Words = Line.Split(Delimiters);
                            foreach (string word in Words)
                                if (word.Length > 0) AllWords.Add(word);
                        }
                    }
                }

                // enable searchtextbox AFTER file is opened
                this.searchTextBox.Enabled = true;
                searchTextBox.Focus();

                // close the file
                inputfile.Close();

                // to display the title & author
                titleText.Text = Title + Author;

                totalAmount.Text = AllWords.Count.ToString("n3");

                wordsListBox.Items.Clear();
                int i = 0;
                while (i < 500)
                {
                    wordsListBox.Items.Add(AllWords[i]);
                    i++;
                }
            }

        }

        private void DisplayList(List<string> wordsListBox)
        {
            foreach (string str in wordsListBox)
            {
                MessageBox.Show(str);
            }

        }

Thank you in advance!

One possible method to find the number of occurrences of a word inside a text is counting the successful results returned by Regex.Matches .

Suppose you have a text file and a word to find inside this text:
(eventually followed by a symbol like .,:)$ etc.)

string text = new StreamReader(@"[SomePath]").ReadToEnd();
string word = "[SomeWord]" + @"(?:$|\W)";

This will return the number of Matches:

int WordCount = Regex.Matches(text, word).Cast<Match>().Count();

This will give you the indexes positions inside the text where those words are found:

List<int> IndexList = Regex.Matches(text, word).Cast<Match>().Select(s => s.Index).ToList();

To perform a case insensitive search, include RegexOptions.IgnoreCase .

Regex.Matches(text, word, RegexOptions.IgnoreCase)


Refine the search patter if this (somewhat generic) is not enough to get the results you want.

You can check the results, creating a list of the Matches, with:

List<string> ListOfWords = Regex.Matches(text, word, RegexOptions.IgnoreCase)
                                .Cast<Match>()
                                .Select(s => s.Value)
                                .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM