How to count characters in RichTextBox using C# - c#

I am new to programming and having problems making a simple code for character counter for a button. I've somehow managed to code a line together that actually counts words. here it is:
private void button_add_Click(object sender, EventArgs e)
{
string count = richTextBox.Text;
label_info.Text = "Word count is " + (count.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Length).ToString();
//Trying to add a new character count down here
// label_info.Text = "Character count is " + ....code ...;
}
Any advice would be appreciated.
EDIT: Thanks to you all i got my answer here:
private void button_add_Click(object sender, EventArgs e)
{
string count = richTextBox.Text;
label_info.Text = "Word count is " + (count.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Length).ToString();
label_info.Text = "\nCharacter count is " + richTextBox.Text.Lenth;
}

Try using string's Length property.
label_info.Text = label_info.Text + "\nCharacter count is " + richTextBox.Text.Lenth;

You are splitting the string on each space and counting the length of the resulting array. If you want the length of the string (with whitespace etc.) you can do this:
label_info.Text = "Character count is " + count.length;
If you don't want the whitespace you can do this:
label_info.Text = "Character count is " + count.Replace(" ", "").length;

You don't have to write a complex code. You can count characters using length property. See below sample codes. In it we use a Textbox and a Label, Label shows the count of characters entered in the textbox.
void textBox1_TextChanged(object sender, EventArgs e)
{
lablename.Text = textboxname.Text.length.Tostring();
}
I have also created its video tutorial. Watch it on YouTube

string a = richTextBox1.Text;
label2.Text = a.Length.ToString();

Related

How to create a function to hold one block of code and then execute?

I have two buttons that contain their own functionality (which I have not included in the code snippet below as it is not relevant), but they also contain the same block of text (which is shown in the code snippet below). My question as I am a beginner in C#, is there a way where I can just write the code once and use the function shall I call to be placed in the buttons instead?
Code Snippet:
private void btnAlpha_Click(object sender, EventArgs e)
{
//Replace Non Alpha code would go here…
/*Count number of lines in processed text,
extra line is always counted so -1 brings it to correct number*/
int numLines = copyText.Split(“/n”).Length - 1;
//seperate certain characters in order to find words
char[] seperator = (" " + nl).ToCharArray();
//number of words, characters and include extra line breaks variable
int numberOfWords = copyText.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;
int numberOfChar = copyText.Length - numLines;
//Unprocessed Summary
newSummary = nl + "Word Count: " + numberOfWords + nl + "Characters Count: " + numberOfChar;
}
private void btnReplace_Click(object sender, EventArgs e)
{
//Replace code would go here…
/*Count number of lines in processed text,
extra line is always counted so -1 brings it to correct number*/
int numLines = copyText.Split(“/n”).Length - 1;
//seperate certain characters in order to find words
char[] seperator = (" " + nl).ToCharArray();
//number of words, characters and include extra line breaks variable
int numberOfWords = copyText.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;
int numberOfChar = copyText.Length - numLines;
//Unprocessed Summary
newSummary = nl + "Word Count: " + numberOfWords + nl + "Characters Count: " + numberOfChar;
}
In C# you can enclose reusable code in methods (as suggested in comments). If there are parts of the code that behave differently then again you can encapsulate them into a separate methods. Below the code that's repeated in each handler is in MyMethod. btnReplace specific code is in MyReplace and btnAlpha specific code is in MyAlpha:
private void btnReplace_Click(object sender, EventArgs e)
{
MyReplace();
MyMethod();
}
private void btnAlpha_Click(object sender, EventArgs e)
{
MyAlpha();
MyMethod();
}
private void MyReplace()
{
// Replace code
}
private void MyAlpha()
{
// Alfa code
}
private void MyMethod()
{
//Replace code would go here…
/*Count number of lines in processed text,
extra line is always counted so -1 brings it to correct number*/
int numLines = copyText.Split(“/n”).Length - 1;
//seperate certain characters in order to find words
char[] seperator = (" " + nl).ToCharArray();
//number of words, characters and include extra line breaks variable
int numberOfWords = copyText.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;
int numberOfChar = copyText.Length - numLines;
//Unprocessed Summary
newSummary = nl + "Word Count: " + numberOfWords + nl + "Characters Count: " + numberOfChar;
}
If you need some sort of communication between the methods then one option would be to return a value from the first method and pass it into the second one.
Alternatively you can parameterize your main method (if true execute alfa part else execute replace part) and execute it with a parameter saying which part of the code to execute. But if there are many possible alternatives than probably producing separate method for each alternative makes more sense.

How a variable can be recognized from button to method?

I'm trying to count the number of words and characters in a specific text. Now this all works fine but I want to tidy up code so that I don't have to include the the you see under newSummaryMethod() into every button, hence why I have placed it in it's own method. But when I do this, it doesn't count the words and characters. Now I know the reason is that string copyText = ""; in the method, that's because if I don't declare that string variable, then I will get syntax errors in my button that copyText is not declared.
My question is really about how can I get the newSummaryMethod to know that it needs to communication with the copyText in first the vowels button? I have another button where copyText may behave a bit differently so I think I need the button to communicate with the method.
private void newSummaryMethod() {
string copyText = "";
/*Count number of lines in processed text,
extra line is always counted so -1 brings it to correct number*/
int numLines = copyText.Split('\n').Length - 1;
//seperate certain characters in order to find words
char[] seperator = (" " + nl).ToCharArray();
//number of words, characters and include extra line breaks variable
int numberOfWords = copyText.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;
int numberOfChar = copyText.Length - numLines;
//Unprocessed Summary
newSummary = nl + "Word Count: " + numberOfWords + nl + "Characters Count: " + numberOfChar;
}
private void btnVowels_Click(object sender, EventArgs e) {
//Strip vowels
string vowels = "AaEeIiOoUu";
string copyText = richTextBox1.Text;
copyText = new string(copyText.Where(c => !vowels.Contains(c)).ToArray());
newSummaryMethod();
//Write into richTextBox2
wholeText = richTextBox1.Text + oldSummary + copyText + newSummary;
Write(Second_File, wholeText);
richTextBox2.Text = wholeText;
}
private void btnAlpha_Click(object sender, EventArgs e) {
//Remove non alpha characters
string nonAlpha = #"[^A-Za-z ]+";
string addSpace = "";
string copyText = richTextBox1.Text;
copyText = Regex.Replace(copyText, nonAlpha, addSpace);
newSummaryMethod();
//Write into richTextBox2
wholeText = richTextBox1.Text + oldSummary + copyText + nl + newSummary;
Write(Second_File, wholeText);
richTextBox2.Text = wholeText;
}
you can pass the data the method needs to it as an argument
private void newSummaryMethod(string copyText) {...}
and then call it like
newSummaryMethod(copyText);
another way is declaring your variable outside the function scope so both functions will have access to it.
string copyText = null; //added
private void newSummaryMethod() {
copyText = ""; //changed
/*Count number of lines in processed text,
extra line is always counted so -1 brings it to correct number*/
int numLines = copyText.Split('\n').Length - 1;
//seperate certain characters in order to find words
char[] seperator = (" " + nl).ToCharArray();
//number of words, characters and include extra line breaks variable
int numberOfWords = copyText.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;
int numberOfChar = copyText.Length - numLines;
//Unprocessed Summary
newSummary = nl + "Word Count: " + numberOfWords + nl + "Characters Count: " + numberOfChar;
}
private void btnVowels_Click(object sender, EventArgs e) {
//Strip vowels
string vowels = "AaEeIiOoUu";
copyText = richTextBox1.Text; //changed
copyText = new string(copyText.Where(c => !vowels.Contains(c)).ToArray());
newSummaryMethod();
//Write into richTextBox2
wholeText = richTextBox1.Text + oldSummary + copyText + newSummary;
Write(Second_File, wholeText);
richTextBox2.Text = wholeText;
}
private void btnAlpha_Click(object sender, EventArgs e) {
//Remove non alpha characters
string nonAlpha = #"[^A-Za-z ]+";
string addSpace = "";
copyText = richTextBox1.Text; //changed
copyText = Regex.Replace(copyText, nonAlpha, addSpace);
newSummaryMethod();
//Write into richTextBox2
wholeText = richTextBox1.Text + oldSummary + copyText + nl + newSummary;
Write(Second_File, wholeText);
richTextBox2.Text = wholeText;
}

How to count the number of words in a string? [duplicate]

This question already has answers here:
Count how many words in each sentence
(8 answers)
Closed 8 years ago.
I want to count the number of words in a string.
Like if given a string:
string str = "Hello! How are you?";
thn the output will be:
Number of words in string “Hello! How are you?” is 4.
I'm using for loop, and these are my current codes.
string wordCountStr = "";
int noOfWords = 0;
private void btn_Computate4_Click(object sender, EventArgs e)
{
wordCountStr = tb_Qns4Input.Text.ToString(); //tb_Qns4Input is a textbox.
for (int i = 0; i< wordCountStr.Length; i++)
{
//I don't know how to code here.
}
lbl_ResultQns4.Text = "Number of words in string " + wordCountStr + " is " + noOfWords;
}
Oh yes, I'm using Microsoft Visual Studio 2013 for my work. So the codes are under a button click event.
Addition:
What are the different methods to code using 'foreach', 'for loops', 'do/while' loops & 'while' loops?
I can only use these 4 loops to my work.
I have solved this question by using these codes:
string wordCountStr = "";
int noOfWords = 0;
private void btn_Computate4_Click(object sender, EventArgs e)
{
wordCountStr = tb_Qns4Input.Text.ToString();
foreach (string sentence in wordCountStr.TrimEnd('.').Split('.'))
{
noOfWords = sentence.Trim().Split(' ').Count();
}
lbl_ResultQns4.Text = "Number of words in ''" + wordCountStr + "'' is " + noOfWords;
}
Assuming perfect input you can simply split on the space and then get the Length of the resulting array.
int count = wordCountStr.Split(' ').Length;

Get last entered word of RichEditControl

How do I get the last entered word in RichEditControl
here my code
private void richEditControl1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == ' ')
{
int wordEndPosition = richEditControl1.Document.CaretPosition.ToInt();
int currentPosition = wordEndPosition;
while (currentPosition > 0 && richEditControl1.Text[currentPosition - 1] != ' ')
{
currentPosition--;
}
string word = richEditControl1.Text.Substring(currentPosition, wordEndPosition - currentPosition);
this.Text = "Last char typed: " + word;
}
}
But when i press Enter create new line, it was wrong.
I guess you want to get a word whether it is surrounded by spaces or new lines, as long as it is the last one? Maybe you should include New Line check in your While loop, so it doesn't check just spaces.
richEditControl1.Text[currentPosition - 1] != "\n"
or something alike. Not sure if "\n" will pass , since I didn't work with such examples for some time. It probably just didn't know what to do whit new line.
Try:
public Form1()
{
InitializeComponent();
richEditControl1.KeyUp +=richEditControl1_Key;
}
private void richEditControl1_Key(object sender, KeyEventArgs e)
{
var currentText = richEditControl1.Text.Replace("\n", "");
currentText = richEditControl1.Text.Replace("\r", " ");
String result = currentText.Trim().Split(' ').LastOrDefault().Trim();
Console.WriteLine(String.Format("{0}| {1}", DateTime.Now.ToLongTimeString(), result));
}

Backslash n "\n" doesn't work?

Hello I am making an application to split the song text based on certain char. The application works when I type something such as "sampletext/ sampletext", then the result should be :
sampletext
sampletext
but, instead of above, the result is
sampletextsampletext
Below is the code :
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = "";
string[] a = TextToSongFormatConverter(textBox1.Text, '/');
textBox2.Text += "\n"; textBox2.Text += "\n"; textBox2.Text += "\n";
foreach (var item in a)
{
textBox2.Text += item;
textBox2.Text += "\n";
}
}
public static string[] TextToSongFormatConverter(string text, char separator)
{
string[] result;
result = text.Split(separator);
for (int i = 0; i < result.Length; i++)
{
result[i] = result[i].Trim();
}
}
I am using visual studio 2012 and c# and windows form :
This is the screenshoot :
Any idea why? Thanks.
Use Environment.NewLine instead. It will give you proper new line characters for system your program is running on.
A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.
from Environment.NewLine Property
Try using Environment.NewLine instead of \n.
MSDN

Categories