WAP How many times 'this' word is available in following paragraph.? [Resolved]

Posted by Kumarkrishna184 under C# on 4/1/2016 | Points: 10 | Views : 251 | Status : [Member] | Replies : 2
Write a logic for How many times 'this' word is available in following paragraph.?

String str="this krishna hi krishna this this ravi ramesh this suresh this";

Thanks and Regards,
Krishna Kumar



Responses

Posted by: A2H on: 4/1/2016 [Member] [MVP] Silver | Points: 50

Up
0
Down

Resolved
Another quick and easy option is to use Regex to count words
String str = "this krishna hi krishna this this ravi ramesh this suresh this"; 

string searchTerm = "this";

// Count the matches, using Regex
int wordCount = Regex.Matches( str, searchTerm ).Count;


Ensure that you added below namespace
using System.Text.RegularExpressions;


Sample Demo : https://dotnetfiddle.net/iqEGXa

Thanks,
A2H
My Blog

Kumarkrishna184, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: A2H on: 4/1/2016 [Member] [MVP] Silver | Points: 25

Up
0
Down
You can use LINQ To count a word in a string like below
//Your string
String str = "this krishna hi krishna this this ravi ramesh this suresh this";

string searchTerm = "this";

//Convert the string into an array of words
string[] source = str.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries);

// Create the query. Use ToLowerInvariant to match "data" and "Data"
var matchQuery = from word in source
where word.ToLowerInvariant() == searchTerm.ToLowerInvariant()
select word;

// Count the matches, which executes the query.
int wordCount = matchQuery.Count();


Ensure that you have added below namespace prior to using above code
using System.Linq;

Source URL : https://msdn.microsoft.com/en-us/library/bb546166.aspx

Demo : https://dotnetfiddle.net/pxEFU2

Thanks,
A2H
My Blog

Kumarkrishna184, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response