Beispiel #1
0
 private void InitSpaceArray(SpaceWeight[] spaceArray)
 {
     for (int i = 0; i < spaceArray.Length; i++)
     {
         spaceArray[i] = new SpaceWeight {
             Spaces = " ", DistanceFromEnd = Math.Min(i, spaceArray.Length - 1 - i)
         };
     }
 }
Beispiel #2
0
        public string Justify(string line, int width)
        {
            if (string.IsNullOrEmpty(line))
            {
                throw new ArgumentNullException("line");
            }
            if (width <= 0)
            {
                throw new ArgumentException("Width must be greater than 0.", "width");
            }

            line = Straighten(line);
            int numberOfSpacesToInsert = width - line.Length;

            string[] wordArray = line.Split(' ');
            if (wordArray.Length == 1)
            {
                return(line);
            }
            if (wordArray.Length == 2)
            {
                return(line);
            }
            if (line.Length >= width)
            {
                return(line);                      //Do not justify line if longer than the requested width
            }
            if (line.Length < width / 2)
            {
                return(line); //Do not justify line if shorter that half of the requested width
            }
            //Create an array of the spaces and justify by adding spaces with highest weight on the middle of the line.
            int numberOfSpaces = wordArray.Length - 1;

            SpaceWeight[] spaceArray = new SpaceWeight[numberOfSpaces];
            InitSpaceArray(spaceArray);
            for (int i = 0; i < numberOfSpacesToInsert; i++)
            {
                AddSpace(spaceArray);
            }

            //Rebuild the line with the justified spaces.
            StringBuilder justifiedLine = new StringBuilder();

            for (int i = 0; i < wordArray.Length; i++)
            {
                justifiedLine.Append(wordArray[i]);
                if (i < wordArray.Length - 1)
                {
                    justifiedLine.Append(spaceArray[i].Spaces);
                }
            }
            return(justifiedLine.ToString());
        }