【发布时间】:2018-04-29 21:55:13
【问题描述】:
我正在努力解决如何在 Visual Studio、C# 中完成我的应用程序... 在允许用户打开文本文件并在 listBox 中显示文本文件的地方,一切都应有尽有。 我的应用程序的一部分还有一个 textBox 和 searchButton,因此用户能够在文本文件中搜索特定单词,然后有一个 outputLabel 应该显示该单词(文本框内的值)在文本文件中出现的次数.
下面是我的 searchButton 的代码,我不知道从哪里开始。
private void searchButton_Click(object sender, EventArgs e)
{
int totalAmount;
totalAmount = AllWords.Count();
}
如果帮助我对你有帮助,她是我的应用程序代码的其余部分(“使用 System.IO;”也在我的代码中,顺便说一句)
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);
}
}
提前谢谢你!
【问题讨论】:
-
这对初学者来说实际上是非常困难的。 LINQ Count Query 的这一侧或执行您自己的搜索循环,似乎没有真正的方法来获取字符串中任何子字符串的计数。不仅如此,字符串还有一些特殊的怪癖:编码、规范化、大小写。这真的取决于你的最终目标有多高。
标签: c# visual-studio filereader