Thursday, April 4, 2013

Write a C# function to find the number of occurrences of a given word in a file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace examples
{
class Program
{
static void Main(string[] args)
{
string find = "tax";
Dictionary myDic = new Dictionary();
StreamReader InputStream = new StreamReader(@"FilePath");
StringBuilder build = new StringBuilder();
build.Append(InputStream.ReadToEnd());
string[] strArr = build.ToString().Split(' ');
for (int i = 0; i < strArr.Length; i++)
{
if (strArr[i].ToLower() == find.ToLower())
{
if (myDic.ContainsKey(find.ToLower()))
{
myDic[strArr[i]]++;
}
else
{
myDic.Add(find.ToLower(), 1);
}
}
}
foreach (var v in myDic)
{
Console.WriteLine("'{0}' occurs {1} times in the input file", find, v.Value);
}
Console.ReadKey();
}
}
}

No comments: