You are currently viewing Write C# code to arrange sentences in the decreasing order of a number of vowels in the sentence.
C# Programming

Write C# code to arrange sentences in the decreasing order of a number of vowels in the sentence.

Write a C# code to arrange sentences in the decreasing order of a number of vowels in the sentence.

Input File:

A file that contains English sentences. Sentences are (of course) separated by the period “.” character.

Problem Statement:

Write a function that takes this file as an input and outputs/writes another file that contains
sentences in the decreasing order of a number of vowels in the sentence.

What should be in the output file?

The first sentence contains the most number of vowels, the second
contains the second-highest number of vowels and so on until the last sentence which contains the
the least number of vowels.

Solution:

public class Program
    {
        
        public static void Main(string[] args)
        {
            string inputFilePath= @"C:\Temp\input.txt";
            string outputFilePath = @"C:\Temp\output.txt";
            FindNArrange(inputFilePath, outputFilePath);
        }
        public static void FindNArrange(string inputFilePath, string outputFilePath)
        {
            string[] outSentences;
            using (StreamReader streamReader = File.OpenText(inputFilePath))
            {
                string text = streamReader.ReadToEnd();
                string[] sentences = text.Split('.');
                var result = from line in sentences
                             select new { line,vowels= CountVowels(line) };
                outSentences = result.OrderByDescending(x => x.vowels).Select(x => x.line).ToArray();
            }
            File.WriteAllText(outputFilePath,String.Join(".", outSentences));
        }
        public static int CountVowels(string line)
        {
            int vowel_count = 0;
            char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
            foreach(var ch in line)
            {
                if (vowels.Contains(ch))
                    vowel_count++;
            }
            return vowel_count;
        }
        
    }

Here is the sample input and output file for your reference.

Input.txt

dfhdkfhskdjfsjadfndkfnksdf. jdsljdlsjdlsldljld. lfjslfjlsdjfljsdlfjlsdlfioe. sdfjsdlfsdjfksdjf dfldsjf dfjsdljflsd e.dlfjlsdjflsdjflsd dkfslnlsdfls sdfjlsdlfsdaoui. dsfjsdkfjksdjfioioe. dfljdslfjsdlklfsaaaa i e.

output.txt

 dfljdslfjsdlklfsaaaa i e. dsfjsdkfjksdjfioioe.dlfjlsdjflsdjflsd dkfslnlsdfls sdfjlsdlfsdaoui. lfjslfjlsdjfljsdlfjlsdlfioe.dfhdkfhskdjfsjadfndkfnksdf. sdfjsdlfsdjfksdjf dfldsjf dfjsdljflsd e. jdsljdlsjdlsldljld.