Click here to Skip to main content
15,890,185 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
my sttring bulilder string would be like this:

StringBuilder sb = new StringBuilder();
sb.Append("hi friends hi");

i want to check the count of "hi" in the sb
so my final output would be like this.

Count is 2.

how to do that.

thank u
SUBIN
Posted
Comments
Mehdi Gholam 18-Apr-13 8:43am    
What have you tried?
kornakar 18-Apr-13 8:43am    
You could use the Split method to split the string with a space (' ') and then loop though the resulting array and count the "hi" words.
[no name] 18-Apr-13 8:49am    
You already asked this in the forums and received an answer. Please do not cross post. Pick one place and stick to it.

1. You need to get String from that StringBuilder.
2. Split string by white-space characters - either use String.Split Method (Char[])[^] or Regex.Split Method (String, String)[^] (in case of Regex you should use compiled regex stored in static readonly field).
3. Filter and count words using LINQ or "manually" in foreach block.
C#
var sb = new StringBuilder("hi friends hi");
var text = sb.ToString();

var words = Regex.Split(text, @"\W");
//var words = text.Split(' ', '\t', '\r', '\n');

var count = words.Where(i => i == "hi").Count();
 
Share this answer
 
v2
Comments
kanamala subin 19-Apr-13 1:48am    
Thank u very much sir...its working....
This might be of help to you:

http://stackoverflow.com/questions/9929279/to-count-the-frequency-of-each-word[^]

Also, if you Google c# count word occurrence, you will get plenty of other possible solutions!

Good luck!
 
Share this answer
 
Hi Mr.Subin

You could do the following:

C#
using System.Text;

namespace SoundTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int count = 0;
            StringBuilder sb = new StringBuilder();
            sb.Append("hi user hi");
            string str = sb.ToString();
            string[] p = str.Split(' ');

            foreach (var item in p)
            {
                if (item == "hi") count++;
            }
            System.Console.WriteLine("count of hi = {0}",count);
        }
    }
}
 
Share this answer
 
Try for this:-


C#
int WordCount(string text)
{
  var regex = new System.Text.RegularExpressions.Regex(@"\w+");

  var matches = regex.Matches(text);
  return matches.Count;
}
 
Share this answer
 

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

  Print Answers RSS


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