ConfusedDeveloper
ConfusedDeveloper

Reputation: 7001

Count occurrence of whole word in a string

I want to find the number of occurrence of particular word in a string.

I have searched online and found many answers like

But none of them gave me accurate result.

What I want is:

Input:

I have asked the question in StackOverflow. Therefore i can expect answer here.

Output for "The" keyword:

The keyword count: 2

Note: It should not consider "The" from "Therefore" in a sentence.

Basically I want to match whole word and get the count.

Upvotes: 1

Views: 11564

Answers (11)

user14261401
user14261401

Reputation: 11

try Like this (Way 1)

string SpecificWord = " the ";
            string sentence = "I have asked the question in StackOverflow. Therefore i can expect answer here.";
            int count = 0;
            foreach (Match match in Regex.Matches(sentence, SpecificWord, RegexOptions.IgnoreCase))
            {
                count++;
            }
            Console.WriteLine("{0}" + " Found " + "{1}" + " Times", SpecificWord, count);

or Like this (Way 2)

string SpecificWord = " the ";
string sentence = "I have asked the question in StackOverflow. Therefore i can expect answer here.";
int WordPlace = sentence.IndexOf(SpecificWord);
Console.WriteLine(sentence);
int TimesRep;
for (TimesRep = 0; WordPlace > -1; TimesRep++)
{
    sentence = (sentence.Substring(0, WordPlace) +sentence.Substring(WordPlace +SpecificWord.Length)).Replace("  ", " ");
    WordPlace = sentence.IndexOf(SpecificWord);
}

Console.WriteLine("this word Found " + TimesRep + " time");

Upvotes: 1

HeavenHM
HeavenHM

Reputation: 992

Try out this works for structured data as well.

    var splitStr = inputStr.Split(' ');
    int result_count = splitStr.Count(str => str.Contains("userName"));

Upvotes: 0

MarcC
MarcC

Reputation: 1

What about (seems more efficency then other solutions):

public static int CountOccurences(string haystack, string needle)
{
    return (haystack.Length - haystack.Replace(needle, string.Empty).Length) / needle.Length;
}

Upvotes: 0

Pappu Kumar
Pappu Kumar

Reputation: 31

There are many possibility for Count occurrence of whole word in a string.
E.g.

First:

string name = "pappu kumar sdffnsd sdfnsdkfbsdf sdfjnsd fsdjkn fsdfsd sdfsd pappu kumar";
var res= name.Contains("pappu kumar");
var splitval = name.Split("pappu kumar").Length-1;

Second:

var r = Regex.Matches(name, "pappu kumar").Count;

Upvotes: 0

Litisqe Kumar
Litisqe Kumar

Reputation: 2564

Try like this

string Text = "I have asked the question in StackOverflow. Therefore i can expect answer here.";
                Text = Text.ToLower();
                Dictionary<string, int> frequencies = null;
                frequencies = new Dictionary<string, int>();
                string[] words = Regex.Split(Text, "\\W+");
                foreach (string word in words)
                {
                    if (frequencies.ContainsKey(word))
                    {
                        frequencies[word] += 1;
                    }
                    else
                    {
                        frequencies[word] = 1;
                    }
                }


                foreach (KeyValuePair<string, int> entry in frequencies)
                {
                    string word = entry.Key;
                    int frequency = entry.Value;
                    Response.Write(word.ToString() + "," + frequency.ToString()+"</br>");
                }

And To search Specific Word then try Like This.

string Text = "I have asked the question in StackOverflow. Therefore the i can expect answer here.";
        Text = Text.ToLower();
        string searchtext = "the";
        searchtext = searchtext.ToLower();
        string[] words = Regex.Split(Text, "\\W+");
        foreach (string word in words)
        {
            if (searchtext.Equals(word))
            {
                count = count + 1;
            }
            else
            {
            }
        }
        Response.Write(count);

Upvotes: 0

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

var searchText=" the ";
var input="I have asked the question in StackOverflow. Therefore i can expect answer here.";
var arr=input.Split(new char[]{' ','.'});
var count=Array.FindAll(arr, s => s.Equals(searchText.Trim())).Length;
Console.WriteLine(count);

DOTNETFIDDLE

EDIT

For your Search Sentence

var sentence ="I have asked the question in StackOverflow. Therefore i can expect answer here.";
var searchText="have asked";
char [] split=new char[]{',',' ','.'};
var splitSentence=sentence.ToLower().Split(split);
var splitText=searchText.ToLower().Split(split);
Console.WriteLine("Search Sentence {0}",splitSentence.Length);
Console.WriteLine("Search Text {0}",splitText.Length);
var count=0;
for(var i=0;i<splitSentence.Length;i++){
    if(splitSentence[i]==splitText[0]){
      var index=i;
        var found=true;
        var j=0;
        for( j=0;j<splitText.Length;j++){
          if(splitSentence[index++]!=splitText[j])
          {
              found=false;
              break;
          }
        }
        if(found){
            Console.WriteLine("Index J {0} ",j);
            count++;
            i= index >i ? index-1 : i;
        }
    }

}
Console.WriteLine("Total found {0} substring",count);

DOTNETFIDDLE

Upvotes: 5

Alexander Petrov
Alexander Petrov

Reputation: 14231

string input = "I have asked the question in StackOverflow. Therefore i can expect answer here.";
string pattern = @"\bthe\b";
var matches = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);
Console.WriteLine(matches.Count);

See Regex Anchors - "\b".

Upvotes: 0

Mark T
Mark T

Reputation: 795

This solution should work wherever the string is:

var str = "I have asked the question in StackOverflow. Therefore i can expect answer here.";
var numMatches = Regex.Matches(str.ToUpper(), "THE")
    .Cast<Match>()
    .Count(match => 
        (match.Index == 0 || str[match.Index - 1] == ' ') && 
        (match.Index + match.Length == str.Length || 
            !Regex.IsMatch(
                str[match.Index + match.Length].ToString(),
                "[a-zA-Z]")));

.NET Fiddle

Upvotes: 0

Alireza
Alireza

Reputation: 10476

Well the problem is not that simple you may think; there are many issues should be taken care of such as punctuation, letter case, and things like how word boundaries are identified. However using N_Gram concept I provide the following solution:

1- Identify how many words are in the key. Name it as N

2- Extract all N-consecutive sequence of words (N_Grams) in the text.

3- Count the occurrence of key in N_Grams

    string text = "I have asked the question in StackOverflow. Therefore i can expect answer here.";
    string key = "the question";
    int gram = key.Split(' ').Count();
    var parts = text.Split(' ');
    List<string> n_grams = new List<string>();
    for (int i = 0; i < parts.Count(); i++)
    {
        if (i <= parts.Count() - gram)
        {
            string sequence = "";
            for (int j = 0; j < gram; j++)
            {
                sequence += parts[i + j] + " ";
            }
            if (sequence.Length > 0)
                sequence = sequence.Remove(sequenc.Count() - 1, 1);
            n_grams.Add(sequence);
        }
    }

    // The result
    int count = n_grams.Count(p => p == key);

}

For example for the key = the question and considering single space as word boundaries, the following bi-grams are extracted:

I have
have asked
asked the
the question
question in
in StackOverflow.
StackOverflow. Therefore
Therefore i
i can
can expect
expect answer
answer here.

and the number of times the question appears in the text is not obvious to see: 1

Upvotes: 0

Ilian Grekov
Ilian Grekov

Reputation: 51

You can use while loop to search index of the first occurrence, after that give search from found index ++ position and set one counter at the end of the loop. While loop goes untill index == -1.

Upvotes: 0

Simon
Simon

Reputation: 1312

A possible solution would be using Regex:

var count = Regex.Matches(input.ToLower(), String.Format("\b{0}\b", "the")).Count;

Upvotes: 2

Related Questions