2016-12-13 22 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 –