Question 12 (2 points) Write a function named uniquewords that counts how many d
ID: 3731927 • Letter: Q
Question
Question 12 (2 points) Write a function named uniquewords that counts how many different words there are in each line of an input file and writes that count to a corresponding line of an output file. The input file already exists when uniqueWords is called. uniquewords creates the output file Input. The function uniquewords takes two parameters: inFile, a string that is the name of a text file that is to be read. The file that inFile refers to contains only lower case letters and white space (no punctuation marks or other special characters) outFile, a string that is the name of the file to which uniqueWords writes its out put The input file is in the current working directory. uniquewords should create the output file in that directory output. For each line of infile, uniquewords should write a corresponding line to outFile containing a single integer: the number of unique words on the If the content of the file turn.txt is below, a time to build up a time to break down a time to dance a time to mourn a time to cast away stones a time to gather stones together the function call uniquewords('turn.txt', 'turnout.txt') should create a file named turnout.txt with this content: 7 5 8Explanation / Answer
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace UniqueWords
{
class Program
{
static int Main(string[] args)
{
string directory = Directory.GetCurrentDirectory();
string inputFileName = String.Concat(directory, @" urn.txt");
bool isUpper = Path.GetFileNameWithoutExtension(inputFileName).Any(c => char.IsUpper(c));
Match matchOptions = Regex.Match(Path.GetFileNameWithoutExtension(inputFileName), "[^a-z0-9\s]", RegexOptions.IgnoreCase);
if (isUpper || matchOptions.Success)
{
Console.WriteLine("Special char's or Upper case letters are not allowed in filename");
return -1;
}
string outputFileName = @"turnOut.txt";
if (File.Exists(outputFileName))
{
File.Delete(outputFileName);
}
Program prog = new Program();
prog.uniqueWords(inputFileName, outputFileName);
Console.ReadLine();
return 1;
}
public void uniqueWords(string inputFileName, string outputFileName)
{
int counter = 0;
string line = string.Empty;
StreamReader inputFile = new StreamReader(inputFileName);
while (null != (line = inputFile.ReadLine()))
{
IList<string> unique = new List<string>();
string[] words = line.Split(new char[0]);
foreach(string word in words)
{
if(!unique.Contains(word))
{
unique.Add(word);
}
}
File.AppendAllLines(outputFileName, new string[] { unique.Count().ToString() });
++counter;
}
inputFile.Close();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.