Finally, the ToolStripMain class implements a word count command similar to the one in some versions of Microsoft Word. This method requires extracting the text in the document and analyzing it to count characters, words, sentences, and paragraphs.
Here is the implementation:
To write code in C#
C# |
Copy Code |
---|---|
void WordCount_Click(object sender, EventArgs e) { int chars = 0; int nonSpaceChars = 0; int words = 0; int paragraphs = 0; int sentences = 0; // calculate statistics string text = Editor.Text; int length = text.Length; for (int i = 0; i < length; i++) { char c = text[i]; // count chars chars++; // count non-space chars if (!char.IsWhiteSpace(c)) { nonSpaceChars++; } // count paragraphs if (c == '\n' || i == length - 1) { if (i == length - 1 || text[i + 1] != '\n') { paragraphs++; } } // count sentences if (c == '.' || c == '!' || c == '?' || i == length - 1) { if (i == length - 1 || char.IsWhiteSpace(text, i + 1)) { sentences++; } } // count words if (char.IsLetterOrDigit(c)) { if (i == length - 1 || !char.IsLetterOrDigit(text, i + 1)) { words++; } } } // show statistics string msg = string.Format( "Words: {0:n0}\r\n" + "Characters: {1:n0}\r\n" + "Non-Space Characters: {2:n0}\r\n" + "Sentences: {3:n0}\r\n" + "Paragraphs: {4:n0}\r\n" + "Average Word Length: {5:n1}\r\n" + "Average Sentence Length: {6:n1}\r\n" + "Average Paragraph Length: {7:n1}\r\n", words, chars, nonSpaceChars, sentences, paragraphs, words > 0 ? nonSpaceChars / (float)words : 0f, sentences > 0 ? nonSpaceChars / (float)sentences : 0f, paragraphs > 0 ? nonSpaceChars / (float)paragraphs : 0f); MessageBox.Show(msg, "Word Count"); } |
The method starts by declaring variables to hold the statistics it will calculate. It then retrieves the document contents as plain text using the Text property, and scans that string counting characters, words, sentences, and paragraphs. Finally, it displays a message box with the statistics.
This sample shows that although the C1Editor supports the rich and powerful XmlDocument object model, you can easily bypass that and get directly to the actual text content when that is convenient. The Text property is similar to the Text property in the RichTextBox control.