Thursday, February 18, 2010

How to find no of occurences of a string in a file using c#?

static int countWordOccurrencesInFile(string filePath, string searchText)
{
// FileStream fstream = File.Open(filePath,FileMode.Open);
using (StreamReader reader = new StreamReader(filePath))
{
string strContents = reader.ReadToEnd();

//Dictionary uniqueWords = new Dictionary();
int occurrences = 0;
int foundPos = -1;
int startIndex = 0;
do
{
foundPos = strContents.IndexOf(searchText, startIndex);
if (foundPos > -1)
{
startIndex = foundPos + 1;
occurrences++;
}
} while (foundPos > -1);

return occurrences;
}
}

No comments:

Post a Comment