Click here to Skip to main content
15,918,041 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I used this code to count characters :
C#
string strsample = "Hello World";
label1.Text = "character count: " + strsample.Length.ToString();


but what code should I use if I want to count words..??



p.s

Wes is this a good description hehe :)
Posted
Updated 20-Jun-19 1:11am
Comments
Sergey Alexandrovich Kryukov 29-Apr-12 17:05pm    
I wonder what do you try?
--SA
h7h7h7 29-Apr-12 17:22pm    
but what code should I use if I want to count words..?

that mean nothing :S

Use RegEx[^] and set pattern to find spaces.

Example in vb:
VB
Module Module1
    Sub Main()
        Dim pattern As String = "[^\w]" 'get all spaces and other signs, like: '.' '?' '!'
        Dim input As String = "This is a nice day. What about this? This tastes good. I saw a dog!"
        Dim words() As String = Nothing, i As Integer = 0, count As Integer = 0
        Console.WriteLine(input)
        words = Regex.Split(input, pattern, RegexOptions.IgnoreCase)
        For i = words.GetLowerBound(0) To words.GetUpperBound(0)
            If words(i).ToString = String.Empty Then count = count - 1
            count = count + 1
        Next
        Console.WriteLine("Count of words:" & count.ToString)

        Console.ReadKey()
    End Sub


And C#:
C#
public static void Main()
{
    string pattern = "[^\\w]";
    //get all spaces and other signs, like: '.' '?' '!'
    string input = "This is a nice day. What about this? This tastes good. I saw a dog!";
    string[] words = null;
    int i = 0;
    int count = 0;
    Console.WriteLine(input);
    words = Regex.Split(input, pattern, RegexOptions.IgnoreCase);
    for (i = words.GetLowerBound(0); i <= words.GetUpperBound(0); i++) {
        if (words[i].ToString() == string.Empty)
            count = count - 1;
        count = count + 1;
    }
    Console.WriteLine("Count of words:" + count.ToString());

    Console.ReadKey();
}



Description seems to be OK ;)
 
Share this answer
 
v4
I think if it is required to count the words accurately, then it is better to list the characters separating the words and use Matches method of Regex and then find out the number of words using the Count property of MatchesCollection found as shown below:
C#
using System.Text.RegularExpressions;
void Main()
{
    string groupOfWords = @"It's a text for counting of words, with different word "+
                           "boundaries and hyphenated word like the all-clear.Is it OK? ";
    var matchesByListedChars = Regex.Matches(groupOfWords,
            @"[^\s.?,]+", RegexOptions.CultureInvariant | RegexOptions.Multiline
            | RegexOptions.IgnoreCase);
    Console.WriteLine ("Word count by listed chars = {0}",
                                    matchesByListedChars.Count);
    var matchesByAlphaNumeric= Regex.Matches(groupOfWords,
            @"[\w]+", RegexOptions.CultureInvariant | RegexOptions.Multiline
            | RegexOptions.IgnoreCase);
    Console.WriteLine ("Word count by alpha numeric pattern: {0}",
                                    matchesByAlphaNumeric.Count);
}
//Output
//Word count by listed chars = 20
//Word count by alpha numeric pattern: 22
//as It's and all-clear are counted as two words each
 
Share this answer
 
v2
Comments
Maciej Los 30-Apr-12 8:22am    
Indeed remark! My 5
Interesting pattern ;)
VJ Reddy 30-Apr-12 8:26am    
Thank you, losmac.
Use the following :
C#
int count = inputstring.Split(' ').Length;
 
Share this answer
 
Comments
Maciej Los 29-Apr-12 18:00pm    
Your answer will be correct, if the words wouldn't be separated with other signs, like: !, @, # and many others.
That's why, i vote for 3.
its pretty simple

C#
//if u r considering only spaces.
int WordCount=1;
foreach(char i in s)
{
 foreach (char i in s)
{
if (char.IsWhiteSpace(i))
WordCount++;
}
}


but words can be separated by spaces,comma,punctuation etc.
so in this case,create a string which contains all word separaters
eg:string Separators=",. \'\"?!";//there are more. add it in any order

now replace
C#
if (char.IsWhiteSpace(i))
WordCount++;

by
C#
if (Separators.Contains(i))
WordCount++;


Print out WordCount at last to get number of words.

this would be the simplest solution :D
 
Share this answer
 
Comments
h7h7h7 29-Apr-12 18:04pm    
I understand now if I want to show number of word in labbel ?
label1.text=.....???? ( what code ? )
h7h7h7 29-Apr-12 18:09pm    
I solved thnx man

I used : label1.text= wordcount.tosring();
Maciej Los 29-Apr-12 18:12pm    
Your answer will be correct, if the words wouldn't be separated with other signs, like: !, @, # and many others. I don't like to search sign by sign.
That's why, i vote for 3.
how to count number of words in a string using c#,Click and get Sample code here
C# Word count | Chars count | Line count in string-SmartSnipp[]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace WordCounter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();      
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StartCount();
        }

        private void StartCount()
        {
            lblChar.Text = "";
            lblWord.Text = "";
            lblLine.Text = "";

            if (txtUserInput.Text != "")
            {
                string useInput = "";
                useInput = txtUserInput.Text.Trim();             

                string pattern = "[^\\w]";
                string input = useInput;

                //word count             
                int i = 0, count = 0;

               string[] words = Regex.Split(input, pattern, RegexOptions.IgnoreCase);
                for (i = words.GetLowerBound(0); i <=words.GetUpperBound(0); i++)
                {
                    if (words[i].ToString() == string.Empty)
                        count = count - 1;
                    count = count + 1;
                }
                lblWord.Text = count.ToString();

                // line count            
                string[] lines = Regex.Split(useInput.Trim(), "\r\n");                
                lblLine.Text = lines.Length.ToString();

                //char count 
                int CharCount = 0;
                foreach (string value in lines)                
                    CharCount += value.Length;
              
                lblChar.Text = CharCount.ToString();  
            }
        }
    }
}
 
Share this answer
 
v2
Comments
Maciej Los 20-Jun-19 7:21am    
This question has been already answered? What your answer differs from accepted solution?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900