2

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; 
}
User_T
  • 247
  • 3
  • 8
  • 18

4 Answers4

1

Try using string's Length property.

label_info.Text = label_info.Text +  "\nCharacter count is " + richTextBox.Text.Lenth;
Bala R
  • 107,317
  • 23
  • 199
  • 210
1

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;
MAV
  • 7,260
  • 4
  • 30
  • 47
  • Oh so the first one counts characters with spaces and the 2nd one without? That's what i needed to know, thanks :) – User_T Apr 14 '13 at 01:14
1

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

1
string a = richTextBox1.Text;
label2.Text = a.Length.ToString();
josliber
  • 43,891
  • 12
  • 98
  • 133
Vinay
  • 11
  • 1