2016-12-13 50 views
-3

我有一个程序,我需要计算已读入richtextbox的文件中有多少女性和男性,但我不知道如何在文件中执行此操作有姓名,性别,具体工作。我有15个不同的人如何计算RichTextbox上的特定字词

例如间数:“唐娜,女,人力资源”,

这是我到目前为止有:

private void Form1_Load(object sender, EventArgs e) 
{ 
    StreamReader sr; 
    richTextBox1.Clear(); 
    sr = new StreamReader("MOCK_DATA.txt"); 
    string data; 
    while (!sr.EndOfStream) 
    { 
     data = sr.ReadLine(); 
     richTextBox1.AppendText(data + "\n"); 
    } 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    string[] data = richTextBox1.Text.Split(','); 
    for (int n = 0; n < data.Length; n++) 
    { 
     if (data[n] == richTextBox1.Text) 
      n++; 

回答

0

要想从纯文本一个RichTextBox(从this article被盗):

string StringFromRichTextBox(RichTextBox rtb) 
{ 
    TextRange textRange = new TextRange(
     // TextPointer to the start of content in the RichTextBox. 
     rtb.Document.ContentStart, 
     // TextPointer to the end of content in the RichTextBox. 
     rtb.Document.ContentEnd 
    ); 

    // The Text property on a TextRange object returns a string 
    // representing the plain text content of the TextRange. 
    return textRange.Text; 
} 

基本字计数规则:

int CountWord(string textToSearch, string word) 
{ 
    int count = 0; 
    int i = textToSearch.IndexOf(word); 
    while (i != -1) 
    { 
     count++; 
     i = textToSearch.IndexOf(word, i+1); 
    } 
    return count; 
} 

将其组合在一起:

var plainText = StringFromRichTextBox(richTextBox1); 
var countOfMale = CountWord(plainText, "Male"); 
var countOfFemale = CountWord(plainText, "Female"); 
+0

我不明白我怎么能算这个代码 –

+0

一个特定的词@LeonardoKafuri没有指定您正在使用的WinForms(添加它的标签),所以你有WPF答案 – Slai

+0

@Slai我正在使用winforms –

相关问题