如何在C#中计算文本文件中的字符串

时间:2019-03-15 14:23:40

标签: c#

在此按钮单击事件中,我试图计算文本文件中与文本框中相同的字符串,然后在标签中显示它们的数量。我的问题是我不知道如何计算它们-我说的是if语句中的代码。我真的很感谢您的帮助。

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();
        }
    }
}

谢谢。

3 个答案:

答案 0 :(得分:1)

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

等等...你在这里说.. 您有一个或多个变量 您访问其属性(计数) 然后将其设置为标签文本(lblResult1.Text)

这就是您要尝试做的吗?因为相反的可能性更大

答案 1 :(得分:0)

使用LINQ,您可以获取出现次数,如下所示:

int numOfOcuurences= s.Count( s=> s == tbFirstClub.Text);
lblResult1.Text = numOfOcuurences.ToString();

答案 2 :(得分:0)

欢迎堆栈溢出。

我想指出你所说的话。

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

S是我们刚刚从文件中读取的字符串。

您说的是文本的关联S.Count(字符串的长度)。

我认为这不是您想要的。我们要返回指定字符串显示在指定文件中的次数 让我们对其进行重构(并在此过程中添加一些技巧)。

// 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;
   }
}

这应该可以解决您的问题,但是仍然很脆弱。理想情况下,我们希望设计一个可以处理任意数量的字符串并对其进行计数的系统。

那我该怎么办?

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;
}

上面的代码使我们可以返回带有任意数量的带计数字符串的数据结构。

我认为这是一个很好的例子,可以帮助您省去以后的麻烦,并且这可能是对设计模式的一次很好的初探。我建议您查找有关数据结构及其用例的一些材料。