Task: Word wrap



C#: namespace RosettaCode.WordWrap
{
    using System;
    using System.Collections.Generic;

    internal static class Program
    {
        private const string LoremIpsum = @"
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt
purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel
felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta
tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed
venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu
nibh.";

        private static void Main()
        {
            foreach (var lineWidth in new[] { 72, 80 })
            {
                Console.WriteLine(new string('-', lineWidth));
                Console.WriteLine(Wrap(LoremIpsum, lineWidth));
            }
        }

        private static string Wrap(string text, int lineWidth)
        {
            return string.Join(string.Empty,
                               Wrap(
                                   text.Split(new char[0],
                                              StringSplitOptions
                                                  .RemoveEmptyEntries),
                                   lineWidth));
        }

        private static IEnumerable<string> Wrap(IEnumerable<string> words,
                                                int lineWidth)
        {
            var currentWidth = 0;
            foreach (var word in words)
            {
                if (currentWidth != 0)
                {
                    if (currentWidth + word.Length < lineWidth)
                    {
                        currentWidth++;
                        yield return " ";
                    }
                    else
                    {
                        currentWidth = 0;
                        yield return Environment.NewLine;
                    }
                }
                currentWidth += word.Length;
                yield return word;
            }
        }
    }
}



Java: package rosettacode;

import java.util.StringTokenizer;

public class WordWrap 
{
    int defaultLineWidth=80;
    int defaultSpaceWidth=1;
    void minNumLinesWrap(String text)
    {
        minNumLinesWrap(text,defaultLineWidth);
    }
    void minNumLinesWrap(String text,int LineWidth)
    {
        StringTokenizer st=new StringTokenizer(text);
        int SpaceLeft=LineWidth;
        int SpaceWidth=defaultSpaceWidth;
        while(st.hasMoreTokens())
        {
            String word=st.nextToken();
            if((word.length()+SpaceWidth)>SpaceLeft)
            {
                System.out.print("\n"+word+" ");
                SpaceLeft=LineWidth-word.length();
            }
            else
            {
                System.out.print(word+" ");
                SpaceLeft-=(word.length()+SpaceWidth);
            }
        }
    }
    public static void main(String[] args)
    {
        WordWrap now=new WordWrap();
        String wodehouse="Old Mr MacFarland (_said Henry_) started the place fifteen years ago. He was a widower with one son and what you might call half a daughter. That's to say, he had adopted her. Katie was her name, and she was the child of a dead friend of his. The son's name was Andy. A little freckled nipper he was when I first knew him--one of those silent kids that don't say much and have as much obstinacy in them as if they were mules. Many's the time, in them days, I've clumped him on the head and told him to do something; and he didn't run yelling to his pa, same as most kids would have done, but just said nothing and went on not doing whatever it was I had told him to do. That was the sort of disposition Andy had, and it grew on him. Why, when he came back from Oxford College the time the old man sent for him--what I'm going to tell you about soon--he had a jaw on him like the ram of a battleship. Katie was the kid for my money. I liked Katie. We all liked Katie.";
        System.out.println("DEFAULT:");
        now.minNumLinesWrap(wodehouse);
        System.out.println("\n\nLINEWIDTH=120");
        now.minNumLinesWrap(wodehouse,120);
    }

}