2

in this button click event I am trying to count strings from text file that are the same as in textboxes, then display number of them in label. My problem is that I have no idea how to count them-I'm talking about code inside if-statement. I would really appreciate any help.

private void btnCalculate_Click(object sender, EventArgs e)
{
    string openFileName;
    using (OpenFileDialog ofd = new OpenFileDialog())
    {
        if (ofd.ShowDialog() != DialogResult.OK)
        {
            MessageBox.Show("You did not select OK");
            return;
        }
        openFileName = ofd.FileName;
    }
    FileStream fs = null;
    StreamReader sr = null;
    try
    {
        fs = new FileStream("x", FileMode.Open, FileAccess.Read);
        fs.Seek(0, SeekOrigin.Begin);
        sr = new StreamReader(fs);
        string s = sr.ReadLine();
        while (s != null)
        {  
            s = sr.ReadLine();
        }
      if(s.Contains(tbFirstClub.Text))
        {
           s.Count = lblResult1.Text; //problem is here
        }
      else if(s.Contains(tbSecondClub.Text))
        {
             s.Count = lblResult2.Text; //problem is here
        }
    }
    catch (IOException)
    {
        MessageBox.Show("Error reading file");
    }
    catch (Exception)
    {
        MessageBox.Show("Something went wrong");
    }
    finally
    {
        if (sr != null)
        {
            sr.Close();
        }
    }
}

Thanks in advance.

BWA
  • 5,672
  • 7
  • 34
  • 45
hsmat
  • 21
  • 2
  • 1
    Possible duplicate of [How would you count occurrences of a string (actually a char) within a string?](https://stackoverflow.com/questions/541954/how-would-you-count-occurrences-of-a-string-actually-a-char-within-a-string) – Magnetron Mar 15 '19 at 14:27

3 Answers3

1
 s.Count = lblResult1.Text; //problem is here

wait...you are saying here.. you have a variable (s) and you access its property (Count) and then set it to the label text(lblResult1.Text)

is that what you're trying to do? because the reverse seems more likely

Dennis Lukas
  • 483
  • 2
  • 6
  • 20
  • In result I expect the user to input string in textbox and here I want to count every string that is the same as the string in text file and put result in label. This whole line of code is probably incorrect – hsmat Mar 15 '19 at 15:33
0

Using LINQ you can get the number of occurences, like below:

int numOfOcuurences= s.Count( s=> s == tbFirstClub.Text);
lblResult1.Text = numOfOcuurences.ToString();
apomene
  • 14,282
  • 9
  • 46
  • 72
  • When I do this I get 2 errors, "CS0136 A local or parameter named 's' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter" and "CS0019 Operator '==' cannot be applied to operands of type 'char' and 'string' " – hsmat Mar 15 '19 at 15:41
0

welcome to Stack Overflow.

I want to point out something you said.

else if(s.Contains(tbSecondClub.Text))
{
    s.Count = lblResult2.Text; //problem is here
}

S is our string that we just read from the file.

You're saying assoung S.Count (The length of the string) to text.

I don't think this is what you want. We want to return the number of times specified strings show up in a specified file Let's refactor this, (And add some tricks along the way).

// Let's create a dictionary to store all of our desired texts, and the counts.
var textAndCounts = new Dictionary<string, int>();
textAndCounts.Add(tbFirstClub.Text, 0); // Assuming the type of Text is string, change acccorrdingly
textAndCounts.Add(tbSecondClub.Text, 0);
//We added both out texts fields to our dictionary with a value of 0

// Read all the lines from the file.
var allLines = File.ReadAllLines(openFileName); /* using System.IO */

foreach(var line in allLines) 
{
   if(line.Contains(tbFirstClub.Text))
   {
       textAndCounts[tbFirstClub.Text] += 1; // Go to where we stored our count for our text and increment
   }
   if(line.Contains(tbSecondClub.Text))
   {
      textandCounts[tbSecondClub.Text] += 1;
   }
}

This should solve your problem, but it's still pretty brittle. Optimally, we want to design a system that works for any number of strings and counts them.

So how would I do it?

public Dictionary<string, int> GetCountsPerStringInFile(IEnumerable<string> textsToSearch, string filePath) 
{
   //Lets use Linq to create a dictionary, assuming all strings are unique.
   //This means, create a dictionary in this list, where the key is the values in the list, and the value is 0 <Text, 0>
   var textsAndCount = textsToSearch.ToDictionary(text => text, count => 0);

   var allLines = File.ReadAllLines(openFileName);
   foreach (var line in allLines)
   {
      // You didn't specify if a line could maintain multiple values, so let's handle that here.
      var keysContained = textsAndCounts.Keys.Where(c => line.Contains(c)); // take all the keys where the line has that key. 
      foreach (var key in keysContained)
      {
         textsAndCounts[key] += 1; // increment the count associated with that string.
      }
   }

   return textsAndCounts;
}

The above code allows us to return a data structure with any amount of strings with a count.

I think this is a good example for you to save you some headaches going forward, and it's probably a good first toe-dip into design patterns. I'd suggest looking up some material on Data structures and their use cases.

Jlalonde
  • 483
  • 4
  • 13