I want to make a program that counts as example the word "Me" from a richtextbox. How is this possible in c#. The code that i already have is that it loads a textfile.
private void button1_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
string strfilename = openFileDialog1.FileName;
string filetext = File.ReadAllText(strfilename);
richTextBox1.Text = filetext;
textBox1.Text = openFileDialog1.FileName;
richTextBox1.LoadFile(@"C:\Users\Administrator\Documents\School\C#\DEEL 2\HW5\5.3 opdracht1\Sonnet 14.txt", RichTextBoxStreamType.PlainText);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
}
If you want to use LINQ, you can do it pretty easily. Simply split the text on whitespaces, and then filter the array for words matching what you want. Here's a sample:
string search = "Me";
int count = richTextBox1.Text.Split(' ').Where(word => word == search).Count();
Separete all the words and after that you can do whatever you want
//Variable to store your count
int n = 0;
string stringToCompare = "Me";
string[] data = richTextBox1.Text.Split(' ');
for(int i=0;i<data.Length;i++)
{
if(data[i]==stringToCompare )
n++;
}
Console.WriteLine($"Word {stringToCompare } has appeared {n} times");
If you dont want case sensitive try something like
if(data[i].ToUpper() == stringToCompare.ToUpper() )
n++;
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.