[EASY] Read More – CodeEval

Here is the problem: https://www.codeeval.com/open_challenges/167/
And here is my solution. I get 92% with this code.

 

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

class ReadMore
{
    public static string line = null;
    static void Main(string[] args)
    {
        List<string> readFile = ReadFile(args[0]);
        
        List<string> formatText = FormatText(readFile);
        
        PrintFormatedText(formatText);
    }

    public static List<string> ReadFile(string fileName)
    {
        List<string> readFileLines = new List<string>();
        StreamReader reader = new StreamReader(fileName);
        line = null;

        using (reader)
        {
            line = reader.ReadLine();

            while (line != null)
            {
                readFileLines.Add(line);
                line = reader.ReadLine();
            }
        }

        return readFileLines;
    }

    public static List<string> FormatText(List<string> fileText)
    {
        List<string> formatTextLines = new List<string>();
        int length = fileText.Count;
        int lineLength = 0;
        string formatLine = null;

        for (int i = 0; i < length; i++)
        {
            line = fileText[i];
            lineLength = line.Length;

            if(lineLength < 55)
            {
                formatTextLines.Add(line);
            }
            else
            {
                String[] words = line.Split(new char[] { ' ', '!', '?' }, StringSplitOptions.RemoveEmptyEntries);
                formatLine = "";
                string tmp = null;
                int count = 0;
                int exit = 0;

                while (exit != -1)
                {
                    tmp = formatLine + " " + words[count];
                    count++;
                    if(tmp.Length <= 40)
                    {
                        formatLine = tmp;
                        
                    }
                    else
                    {
                        exit = -1;
                    }
                }

                formatLine = formatLine.TrimStart(new char[] { ' ' });
                formatLine += "... <Read More>";
                formatTextLines.Add(formatLine);
            }
        }

        return formatTextLines;
    }

    public static void PrintFormatedText(List<string> formatedText)
    {
        foreach (var line in formatedText)
        {
            Console.WriteLine(line);
        }
    }
}

Leave a comment