Make a simple word wrapper











up vote
16
down vote

favorite
3












(Note: This is my first ever code golf question, but as far as I can tell, nobody else has done exactly this, so I should be good.)



Your task is to make a program or function that takes in a string s and an integer n, and returns or outputs that text wrapped into multiple lines. Each word must be wholly on a line; i.e. no words split in the middle. Each line can be no longer than n characters long, and you must fit as many words as possible on each line.



Example:



s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat." 
n = 50

output:
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed eget erat lectus. Morbi mi mi, fringilla
sed suscipit ullamcorper, tristique at mauris.
Morbi non commodo nibh. Pellentesque habitant
morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Sed at iaculis mauris.
Praesent a sem augue. Nulla lectus sapien, auctor
nec pharetra eu, tincidunt ac diam. Sed ligula
arcu, aliquam quis velit aliquam, dictum varius
erat.


Your output can be an array of strings or a single string with line breaks. Also, you can assume no words will be longer than n, so don't worry about dealing with weird cases.



Standard I/O rules apply, and standard loopholes are prohibited. Trailing spaces are allowed.



Since this is code-golf, the shortes solution in bytes wins.



Here is an example program in Python that would work.










share|improve this question
























  • Format a list of words
    – user202729
    Dec 1 at 1:49








  • 2




    n is the max line length ? or the length we have to reach before line break ?
    – david
    2 days ago






  • 1




    @david, or the number of lines?
    – Peter Taylor
    2 days ago






  • 1




    28 bytes Python is it relevant?
    – david
    2 days ago






  • 2




    n is the max line length, sorry that that was not clear. I will clarify. Also, the rules have now been updated so a simple split doesn't work.
    – ATMunn
    2 days ago















up vote
16
down vote

favorite
3












(Note: This is my first ever code golf question, but as far as I can tell, nobody else has done exactly this, so I should be good.)



Your task is to make a program or function that takes in a string s and an integer n, and returns or outputs that text wrapped into multiple lines. Each word must be wholly on a line; i.e. no words split in the middle. Each line can be no longer than n characters long, and you must fit as many words as possible on each line.



Example:



s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat." 
n = 50

output:
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed eget erat lectus. Morbi mi mi, fringilla
sed suscipit ullamcorper, tristique at mauris.
Morbi non commodo nibh. Pellentesque habitant
morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Sed at iaculis mauris.
Praesent a sem augue. Nulla lectus sapien, auctor
nec pharetra eu, tincidunt ac diam. Sed ligula
arcu, aliquam quis velit aliquam, dictum varius
erat.


Your output can be an array of strings or a single string with line breaks. Also, you can assume no words will be longer than n, so don't worry about dealing with weird cases.



Standard I/O rules apply, and standard loopholes are prohibited. Trailing spaces are allowed.



Since this is code-golf, the shortes solution in bytes wins.



Here is an example program in Python that would work.










share|improve this question
























  • Format a list of words
    – user202729
    Dec 1 at 1:49








  • 2




    n is the max line length ? or the length we have to reach before line break ?
    – david
    2 days ago






  • 1




    @david, or the number of lines?
    – Peter Taylor
    2 days ago






  • 1




    28 bytes Python is it relevant?
    – david
    2 days ago






  • 2




    n is the max line length, sorry that that was not clear. I will clarify. Also, the rules have now been updated so a simple split doesn't work.
    – ATMunn
    2 days ago













up vote
16
down vote

favorite
3









up vote
16
down vote

favorite
3






3





(Note: This is my first ever code golf question, but as far as I can tell, nobody else has done exactly this, so I should be good.)



Your task is to make a program or function that takes in a string s and an integer n, and returns or outputs that text wrapped into multiple lines. Each word must be wholly on a line; i.e. no words split in the middle. Each line can be no longer than n characters long, and you must fit as many words as possible on each line.



Example:



s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat." 
n = 50

output:
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed eget erat lectus. Morbi mi mi, fringilla
sed suscipit ullamcorper, tristique at mauris.
Morbi non commodo nibh. Pellentesque habitant
morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Sed at iaculis mauris.
Praesent a sem augue. Nulla lectus sapien, auctor
nec pharetra eu, tincidunt ac diam. Sed ligula
arcu, aliquam quis velit aliquam, dictum varius
erat.


Your output can be an array of strings or a single string with line breaks. Also, you can assume no words will be longer than n, so don't worry about dealing with weird cases.



Standard I/O rules apply, and standard loopholes are prohibited. Trailing spaces are allowed.



Since this is code-golf, the shortes solution in bytes wins.



Here is an example program in Python that would work.










share|improve this question















(Note: This is my first ever code golf question, but as far as I can tell, nobody else has done exactly this, so I should be good.)



Your task is to make a program or function that takes in a string s and an integer n, and returns or outputs that text wrapped into multiple lines. Each word must be wholly on a line; i.e. no words split in the middle. Each line can be no longer than n characters long, and you must fit as many words as possible on each line.



Example:



s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat." 
n = 50

output:
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed eget erat lectus. Morbi mi mi, fringilla
sed suscipit ullamcorper, tristique at mauris.
Morbi non commodo nibh. Pellentesque habitant
morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Sed at iaculis mauris.
Praesent a sem augue. Nulla lectus sapien, auctor
nec pharetra eu, tincidunt ac diam. Sed ligula
arcu, aliquam quis velit aliquam, dictum varius
erat.


Your output can be an array of strings or a single string with line breaks. Also, you can assume no words will be longer than n, so don't worry about dealing with weird cases.



Standard I/O rules apply, and standard loopholes are prohibited. Trailing spaces are allowed.



Since this is code-golf, the shortes solution in bytes wins.



Here is an example program in Python that would work.







code-golf string






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 days ago

























asked Dec 1 at 1:36









ATMunn

1118




1118












  • Format a list of words
    – user202729
    Dec 1 at 1:49








  • 2




    n is the max line length ? or the length we have to reach before line break ?
    – david
    2 days ago






  • 1




    @david, or the number of lines?
    – Peter Taylor
    2 days ago






  • 1




    28 bytes Python is it relevant?
    – david
    2 days ago






  • 2




    n is the max line length, sorry that that was not clear. I will clarify. Also, the rules have now been updated so a simple split doesn't work.
    – ATMunn
    2 days ago


















  • Format a list of words
    – user202729
    Dec 1 at 1:49








  • 2




    n is the max line length ? or the length we have to reach before line break ?
    – david
    2 days ago






  • 1




    @david, or the number of lines?
    – Peter Taylor
    2 days ago






  • 1




    28 bytes Python is it relevant?
    – david
    2 days ago






  • 2




    n is the max line length, sorry that that was not clear. I will clarify. Also, the rules have now been updated so a simple split doesn't work.
    – ATMunn
    2 days ago
















Format a list of words
– user202729
Dec 1 at 1:49






Format a list of words
– user202729
Dec 1 at 1:49






2




2




n is the max line length ? or the length we have to reach before line break ?
– david
2 days ago




n is the max line length ? or the length we have to reach before line break ?
– david
2 days ago




1




1




@david, or the number of lines?
– Peter Taylor
2 days ago




@david, or the number of lines?
– Peter Taylor
2 days ago




1




1




28 bytes Python is it relevant?
– david
2 days ago




28 bytes Python is it relevant?
– david
2 days ago




2




2




n is the max line length, sorry that that was not clear. I will clarify. Also, the rules have now been updated so a simple split doesn't work.
– ATMunn
2 days ago




n is the max line length, sorry that that was not clear. I will clarify. Also, the rules have now been updated so a simple split doesn't work.
– ATMunn
2 days ago










23 Answers
23






active

oldest

votes

















up vote
6
down vote














Python 2, 26 bytes





from textwrap import*
fill


Try it online!



Meh... built-ins are boring... instead, have a nice 87-byte solution here:



s,n=input()
x=''
for i in s.split():c=n<len(x+i);exec'print x'*c;x=x*-~-c+i+' '
print x


Try it online!



Outputs trailing spaces.






share|improve this answer






























    up vote
    5
    down vote














    Perl 6, 46 29 bytes





    {;*.comb(/.**{1..$_}[s|$]/)}


    Try it online!



    Regex based solution that takes input curried, like f(n)(s) and returns a list of lines. Each line except the last has a trailing whitespace



    Explanation:



    {;*                         }   # Anonymous code block that returns a Whatever lambda
    .comb(/ /) # Split the string by
    .**{1..$_} # Up to n characters
    [s|$] # Terminated by a whitespace char or the end of the string





    share|improve this answer






























      up vote
      4
      down vote














      PHP, 8 bytes



      Admittedly not the most original solution, but PHP has a native function that matches your requirements perfectly!




      wordwrap:




      string wordwrap ( string $str [, int $width = 75 [, string $break = "n" [, bool $cut = FALSE ]]] )



      Wraps a string to a given number of characters using a string break character.




      Use like so:





      $str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.";
      echo wordwrap($str, 50);


      Or Try it online!






      share|improve this answer






























        up vote
        4
        down vote













        JavaScript (ES6),  75 73  72 bytes



        Takes input as (string)(n).





        s=>n=>s.split` `.map(w=>r=(u=r?r+' '+w:w)[n]?(o+=r+`
        `,w):u,o=r='')&&o+r


        Try it online!



        Variables



        The formatted output is stored in $o$ (in green below).



        The updated line $u$ is defined as the concatenation of:




        • the current line $r$ (in black below)

        • a space if $r$ is not empty, or nothing otherwise (in orange below)

        • the new word $w$ (in blue below)


        We need to insert a line break whenever the $n$-th character of $u$ is set (0-indexed, in red below).



        Example



        $n=16$ and $s$ = "LOREM IPSUM DOLOR"



        Adding "LOREM":
        $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
        hline
        00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
        color{blue}L&color{blue}O&color{blue}R&color{blue}E&color{blue}M&&&&&&&&&&&&\ hlineend{array}
        $$



        Adding "IPSUM":
        $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
        hline
        00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
        L&O&R&E&M&color{orange}bullet&color{blue}I&color{blue}P&color{blue}S&color{blue}U&color{blue}M&&&&&&\ hlineend{array}
        $$



        Adding "DOLOR":
        $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
        hline
        00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
        L&O&R&E&M&bullet&I&P&S&U&M&color{orange}bullet&color{blue}D&color{blue}O&color{blue}L&color{blue}O&color{blue}R\ hlineend{array}
        $$



        $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
        hline
        00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
        color{green}L&color{green}O&color{green}R&color{green}E&color{green}M&color{green}bullet&color{green}I&color{green}P&color{green}S&color{green}U&color{green}M&color{green}hookleftarrow&&&&&\ hline
        D&O&L&O&R&&&&&&&&&&&&\ hlineend{array}
        $$






        share|improve this answer























        • Trailing spaces are allowed. maybe r+w+' '?
          – l4m2
          yesterday


















        up vote
        4
        down vote













        Vim, 15 bytes/keystrokes



        DJ:se tw=<C-r>"
        gq_


        A text formatting question? I know just the tool for the job! And it even has my name in the first two keystrokes :D



        <C-r> means ctrl-r.



        This could ever so slightly shorter in V, but I prefer answering in vanilla vim for answers that really show off how concise vim can be for the right challenge. And the difference is so small anyway.



        This could also be the following for 15 bytes as well:



        :se tw=<C-r><C-w>
        ddgq_


        Try it online!






        share|improve this answer



















        • 1




          Explanation: DJ:: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]
          – Erik the Outgolfer
          2 days ago


















        up vote
        4
        down vote














        Haskell, 70 bytes





        s!n|length s<=n=[s]|(t,_:d)<-splitAt(until((<'!').(s!!))pred n)s=t:d!n





        share|improve this answer






























          up vote
          3
          down vote














          Python 2, 74 bytes





          s,n=input()
          while s:i=n;exec"i-=' '<(s+' '*n)[i];"*n;print s[:i];s=s[i+1:]


          Try it online!






          share|improve this answer




























            up vote
            2
            down vote














            R, 36 27 bytes



            R has this as a built-in (strwrap), we return a vector of split lines.





            function(s,n)strwrap(s,n+1)


            Try it online!






            share|improve this answer



















            • 1




              Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
              – ATMunn
              2 days ago


















            up vote
            1
            down vote














            Retina 0.8.2, 37 bytes



            .+$
            $*
            !`(?=S.*¶(1)+)(?<-1>.)+(?=s)


            Try it online! Takes s and n on separate lines. Explanation:



            .+$
            $*


            Convert n to unary.



            (?=S.*¶(1)+)(?<-1>.)+(?=s)


            Match non-whitespace, then look ahead to n and count it as $#1. Then go back and use a balancing group to match up to n characters followed by whitespace.



            !`


            Output the matches as a list of lines.






            share|improve this answer




























              up vote
              1
              down vote














              Charcoal, 19 bytes



              Nθ←F⪪S «¿‹⁺LιⅈθM→⸿ι


              Try it online! Link is to verbose version of code. Takes input of n and s on separate lines. Explanation:



              Nθ


              Input n.






              Move the cursor left one square to balance the right movement from the first iteration of the loop.



              F⪪S «


              Split the string on spaces and loop over the words.



              ¿‹⁺Lιⅈθ


              Calculate whether the next word will reach the right edge.



              M→


              If it will not then move one square right.



              ⸿


              If it will then start a new line.



              ι


              Output the word.






              share|improve this answer




























                up vote
                1
                down vote














                Red, 125, 117, 114 112 bytes



                func[s n][d: 0 parse s[any[to" "p:" "opt[[to" "| to end]q:(if(-1 - d + index? q)> n[p/1: #"^/"d: index? p])]]]s]


                Try it online!






                share|improve this answer






























                  up vote
                  1
                  down vote













                  JavaScript, 39 bytes





                  s=>n=>eval(`s.match(/.{1,${n}} |.+/g)`)


                  Try it online!






                  share|improve this answer























                  • Fail at the end
                    – l4m2
                    yesterday










                  • @l4m2 fixed....
                    – tsh
                    yesterday


















                  up vote
                  1
                  down vote













                  Powershell, 40 83 bytes



                  Test case with n=80 added.





                  param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
                  $o


                  Test script:



                  $f = {

                  param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
                  $o

                  }

                  @(
                  ,(50, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
                  "Lorem ipsum dolor sit amet, consectetur adipiscing",
                  "elit. Sed eget erat lectus. Morbi mi mi, fringilla",
                  "sed suscipit ullamcorper, tristique at mauris.",
                  "Morbi non commodo nibh. Pellentesque habitant",
                  "morbi tristique senectus et netus et malesuada",
                  "fames ac turpis egestas. Sed at iaculis mauris.",
                  "Praesent a sem augue. Nulla lectus sapien, auctor",
                  "nec pharetra eu, tincidunt ac diam. Sed ligula",
                  "arcu, aliquam quis velit aliquam, dictum varius",
                  "erat.")
                  ,(80, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
                  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus.",
                  "Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non",
                  "commodo nibh. Pellentesque habitant morbi tristique senectus et netus et",
                  "malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue.",
                  "Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu,",
                  "aliquam quis velit aliquam, dictum varius erat.")
                  ) | %{
                  $n,$s,$expected = $_
                  $result = &$f $s $n
                  "$result"-eq"$expected"
                  # $result # uncomment this line to dispaly a result
                  }


                  Output:



                  True
                  True





                  share|improve this answer






























                    up vote
                    1
                    down vote














                    Japt, 24 bytes



                    ¸r@[XY]q(X·Ì+S+Y Ê>V?R:S


                    Try it online!



                    Thanks to Bubbler for removing some duplication.



                    Explanation:



                    ¸                           :Split into words
                    r@ :Reduce back into a string by:
                    X : Start with the already reduced portion
                    ·Ì : Get the last line
                    +S+Y : Add a space and the next word
                    Ê>V? : If the length of that line is greater than n:
                    R : Choose newline
                    : : Otherwise:
                    S : Choose space
                    [XY]q( : Join the next word to the result using the chosen character





                    share|improve this answer























                    • 24 bytes with [X,Y].join(...).
                      – Bubbler
                      yesterday


















                    up vote
                    0
                    down vote













                    Bash/Coreutils, 8 bytes



                    fold -sw <n>


                    Try It Online!



                    The fold utility, that's bundled along with coreutils, does exactly what the question asks. The -s flag makes it so that it only breaks on whitespaces(ie. when the word ends), the value of n is passed using the argument -w. Input is accepted via stdin






                    share|improve this answer























                    • Unfortunately, that doesn't work for the test case from the question, because fold counts a trailing space as one of the 50 bytes.
                      – Dennis
                      2 days ago










                    • On a side note, only full programs and functions are allowed by default. fold -sw$1 (or fold -s$1) would comply with that rule.
                      – Dennis
                      2 days ago


















                    up vote
                    0
                    down vote













                    Thanks to @Erik the Outgolfer, a golfed version :




                    Python 3, 94 bytes





                    def f(t,n):
                    while t:i=n+(t[min(len(t)-1,n)]==" "or-t[n-1::-1].find(' '));print(t[:i]);t=t[i:]


                    Try it online!



                    # Python 3, 130 bytes





                    def f(t,n):
                    l=
                    while len(t):
                    i=(n-t[:n][::-1].find(' '),n+1)[t[min(len(t)-1,n)]==" "]
                    l.append(t[:i])
                    t=t[i::]
                    return l


                    Try it online!



                    Not so golfed version...






                    share|improve this answer



















                    • 1




                      Some golfs. (prints to STDOUT, doesn't return).
                      – Erik the Outgolfer
                      2 days ago


















                    up vote
                    0
                    down vote













                    JavaScript + HTML + CSS, 117 64 bytes



                    -53 bytes courtesy of @Neil






                    n=50
                    s="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
                    f=(n,s)=>document.body.innerHTML+=`<tt><p style=width:${n}ch>${s}`
                    f(n,s)








                    share|improve this answer



















                    • 1




                      At least in my browser you can cut this down to (n,s)=>document.body.innerHTML+=`<p style=width:${n}ch><tt>${s}</tt></p>` for 74 bytes. If you're willing to dig out old versions of Firefox you can save another 8 bytes with (n,s)=>document.body.innerHTML+=`<pre wrap width=${n}>${s}</pre>` .
                      – Neil
                      2 days ago










                    • @Neil Nice use of ch units. Firefox 65 computes 50ch as 500px; Chromium 70 computes 50ch as 400px
                      – guest271314
                      2 days ago










                    • This answer is wrong. elit. Sed eget erat lectus. Morbi mi mi, fringilla sed (2nd line) is more than 50 characters. I'm using the newest Chrome.
                      – mbomb007
                      2 days ago












                    • I was able to tweak my original suggestion to work in Chrome by putting the <p> inside the <tt>.
                      – Neil
                      2 days ago






                    • 1




                      next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
                      – Neil
                      2 days ago


















                    up vote
                    0
                    down vote














                    C# (Visual C# Interactive Compiler), 91 bytes





                    s=>n=>s.Split(' ').Aggregate((a,w)=>a+(a.Length-a.LastIndexOf('n')+w.Length>n?'n':' ')+w)


                    Try it online!






                    share|improve this answer




























                      up vote
                      0
                      down vote













                      Mathematica, 16 bytes



                      InsertLinebreaks


                      Built-in function. Takes a string and an integer as input and returns a string as output.




                      InsertLinebreaks["string", n]

                       inserts newline characters to make no line longer than n characters.







                      share|improve this answer






























                        up vote
                        0
                        down vote














                        Jelly, 12 bytes



                        ḲŒṖK€€ḣ€ƑƇṪY


                        Try it online!



                        Unfortunately, this is too slow to work for the provided test case in under a minute over TIO.






                        share|improve this answer




























                          up vote
                          0
                          down vote














                          C# (.NET Core), 162 bytes





                          stringt(string n,int a){var g="";for(int i=0;i++<Math.Floor((double)n.Length/a);)g+=$"^.{{{i*a-1}}}|";return Regex.Split(n,$@"(?n)(?<=({g.Trim('|')})S*)s");}}


                          This function uses a regex which matches the closest whitespace that is near the nth or multiple of nth character and splits the string based on it.



                          Try it online!



                          The TIO link is a full program, and the function has a static keyword so the function can be called from main.



                          Test Regex






                          share|improve this answer























                          • This doesn't give the right output for the test case - some lines are longer than 50 characters. You want "before" not "near", and also the splitting at one point must depend on where it was split earlier.
                            – Ørjan Johansen
                            20 hours ago




















                          up vote
                          0
                          down vote














                          05AB1E, 18 bytes



                          õs#vDy«g²›i,}yðJ}?


                          Try it online.



                          Explanation:





                          õ                   # Push an empty string "" to the stack
                          s # Swap to take the (implicit) string input
                          # # Split it by spaces
                          v } # For-each `y` over the words:
                          D # Duplicate the top of the stack
                          # (which is the empty string in the very first iteration)
                          y« # Append the current word `y`
                          g # Get its length
                          ²›i } # If its lengthy is larger than the second input:
                          , # Pop and output the current duplicated value with trailing newline
                          yð # Push the word `y` and a space " "
                          J # Join the entire stack together
                          ? # After the loop, output the last part as well (without newline)





                          share|improve this answer




























                            up vote
                            0
                            down vote













                            Java 8, 135 bytes





                            n->s->{String r="",S=s.split(" "),t=r;for(int i=0;i<S.length;)if((t+S[i]).length()>n){r+=t+"n";t="";}else t+=S[i++]+" ";return r+t;}


                            Try it online.



                            Explanation:



                            n->s->{                      // Method with integer & String parameters and String return
                            String r="", // Result-String, starting empty
                            S=s.split(" "), // Input-String split by spaces
                            t=r; // Temp-String, starting empty as well
                            for(int i=0;i<S.length;) // Loop `i` in the range [0, amount_of_words):
                            if((t+S[i]).length()>n){ // If `t` and the word are larger than the integer input:
                            r+=t+"n"; // Add `t` and a newline to the result
                            t="";} // And reset `t` to an empty String
                            else // Else:
                            t+=S[i++]+" "; // Append the word and a space to `t`
                            // (and then increase `i` by 1 with `i++` for the next word
                            // of the next iteration)
                            return r+t;} // Return the result-String appended with `t` as result





                            share|improve this answer





















                              Your Answer





                              StackExchange.ifUsing("editor", function () {
                              return StackExchange.using("mathjaxEditing", function () {
                              StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
                              StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
                              });
                              });
                              }, "mathjax-editing");

                              StackExchange.ifUsing("editor", function () {
                              StackExchange.using("externalEditor", function () {
                              StackExchange.using("snippets", function () {
                              StackExchange.snippets.init();
                              });
                              });
                              }, "code-snippets");

                              StackExchange.ready(function() {
                              var channelOptions = {
                              tags: "".split(" "),
                              id: "200"
                              };
                              initTagRenderer("".split(" "), "".split(" "), channelOptions);

                              StackExchange.using("externalEditor", function() {
                              // Have to fire editor after snippets, if snippets enabled
                              if (StackExchange.settings.snippets.snippetsEnabled) {
                              StackExchange.using("snippets", function() {
                              createEditor();
                              });
                              }
                              else {
                              createEditor();
                              }
                              });

                              function createEditor() {
                              StackExchange.prepareEditor({
                              heartbeatType: 'answer',
                              convertImagesToLinks: false,
                              noModals: true,
                              showLowRepImageUploadWarning: true,
                              reputationToPostImages: null,
                              bindNavPrevention: true,
                              postfix: "",
                              imageUploader: {
                              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                              allowUrls: true
                              },
                              onDemand: true,
                              discardSelector: ".discard-answer"
                              ,immediatelyShowMarkdownHelp:true
                              });


                              }
                              });














                              draft saved

                              draft discarded


















                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f176870%2fmake-a-simple-word-wrapper%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown

























                              23 Answers
                              23






                              active

                              oldest

                              votes








                              23 Answers
                              23






                              active

                              oldest

                              votes









                              active

                              oldest

                              votes






                              active

                              oldest

                              votes








                              up vote
                              6
                              down vote














                              Python 2, 26 bytes





                              from textwrap import*
                              fill


                              Try it online!



                              Meh... built-ins are boring... instead, have a nice 87-byte solution here:



                              s,n=input()
                              x=''
                              for i in s.split():c=n<len(x+i);exec'print x'*c;x=x*-~-c+i+' '
                              print x


                              Try it online!



                              Outputs trailing spaces.






                              share|improve this answer



























                                up vote
                                6
                                down vote














                                Python 2, 26 bytes





                                from textwrap import*
                                fill


                                Try it online!



                                Meh... built-ins are boring... instead, have a nice 87-byte solution here:



                                s,n=input()
                                x=''
                                for i in s.split():c=n<len(x+i);exec'print x'*c;x=x*-~-c+i+' '
                                print x


                                Try it online!



                                Outputs trailing spaces.






                                share|improve this answer

























                                  up vote
                                  6
                                  down vote










                                  up vote
                                  6
                                  down vote










                                  Python 2, 26 bytes





                                  from textwrap import*
                                  fill


                                  Try it online!



                                  Meh... built-ins are boring... instead, have a nice 87-byte solution here:



                                  s,n=input()
                                  x=''
                                  for i in s.split():c=n<len(x+i);exec'print x'*c;x=x*-~-c+i+' '
                                  print x


                                  Try it online!



                                  Outputs trailing spaces.






                                  share|improve this answer















                                  Python 2, 26 bytes





                                  from textwrap import*
                                  fill


                                  Try it online!



                                  Meh... built-ins are boring... instead, have a nice 87-byte solution here:



                                  s,n=input()
                                  x=''
                                  for i in s.split():c=n<len(x+i);exec'print x'*c;x=x*-~-c+i+' '
                                  print x


                                  Try it online!



                                  Outputs trailing spaces.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited 2 days ago

























                                  answered 2 days ago









                                  Erik the Outgolfer

                                  30.9k429102




                                  30.9k429102






















                                      up vote
                                      5
                                      down vote














                                      Perl 6, 46 29 bytes





                                      {;*.comb(/.**{1..$_}[s|$]/)}


                                      Try it online!



                                      Regex based solution that takes input curried, like f(n)(s) and returns a list of lines. Each line except the last has a trailing whitespace



                                      Explanation:



                                      {;*                         }   # Anonymous code block that returns a Whatever lambda
                                      .comb(/ /) # Split the string by
                                      .**{1..$_} # Up to n characters
                                      [s|$] # Terminated by a whitespace char or the end of the string





                                      share|improve this answer



























                                        up vote
                                        5
                                        down vote














                                        Perl 6, 46 29 bytes





                                        {;*.comb(/.**{1..$_}[s|$]/)}


                                        Try it online!



                                        Regex based solution that takes input curried, like f(n)(s) and returns a list of lines. Each line except the last has a trailing whitespace



                                        Explanation:



                                        {;*                         }   # Anonymous code block that returns a Whatever lambda
                                        .comb(/ /) # Split the string by
                                        .**{1..$_} # Up to n characters
                                        [s|$] # Terminated by a whitespace char or the end of the string





                                        share|improve this answer

























                                          up vote
                                          5
                                          down vote










                                          up vote
                                          5
                                          down vote










                                          Perl 6, 46 29 bytes





                                          {;*.comb(/.**{1..$_}[s|$]/)}


                                          Try it online!



                                          Regex based solution that takes input curried, like f(n)(s) and returns a list of lines. Each line except the last has a trailing whitespace



                                          Explanation:



                                          {;*                         }   # Anonymous code block that returns a Whatever lambda
                                          .comb(/ /) # Split the string by
                                          .**{1..$_} # Up to n characters
                                          [s|$] # Terminated by a whitespace char or the end of the string





                                          share|improve this answer















                                          Perl 6, 46 29 bytes





                                          {;*.comb(/.**{1..$_}[s|$]/)}


                                          Try it online!



                                          Regex based solution that takes input curried, like f(n)(s) and returns a list of lines. Each line except the last has a trailing whitespace



                                          Explanation:



                                          {;*                         }   # Anonymous code block that returns a Whatever lambda
                                          .comb(/ /) # Split the string by
                                          .**{1..$_} # Up to n characters
                                          [s|$] # Terminated by a whitespace char or the end of the string






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited yesterday

























                                          answered 2 days ago









                                          Jo King

                                          19.9k245105




                                          19.9k245105






















                                              up vote
                                              4
                                              down vote














                                              PHP, 8 bytes



                                              Admittedly not the most original solution, but PHP has a native function that matches your requirements perfectly!




                                              wordwrap:




                                              string wordwrap ( string $str [, int $width = 75 [, string $break = "n" [, bool $cut = FALSE ]]] )



                                              Wraps a string to a given number of characters using a string break character.




                                              Use like so:





                                              $str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.";
                                              echo wordwrap($str, 50);


                                              Or Try it online!






                                              share|improve this answer



























                                                up vote
                                                4
                                                down vote














                                                PHP, 8 bytes



                                                Admittedly not the most original solution, but PHP has a native function that matches your requirements perfectly!




                                                wordwrap:




                                                string wordwrap ( string $str [, int $width = 75 [, string $break = "n" [, bool $cut = FALSE ]]] )



                                                Wraps a string to a given number of characters using a string break character.




                                                Use like so:





                                                $str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.";
                                                echo wordwrap($str, 50);


                                                Or Try it online!






                                                share|improve this answer

























                                                  up vote
                                                  4
                                                  down vote










                                                  up vote
                                                  4
                                                  down vote










                                                  PHP, 8 bytes



                                                  Admittedly not the most original solution, but PHP has a native function that matches your requirements perfectly!




                                                  wordwrap:




                                                  string wordwrap ( string $str [, int $width = 75 [, string $break = "n" [, bool $cut = FALSE ]]] )



                                                  Wraps a string to a given number of characters using a string break character.




                                                  Use like so:





                                                  $str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.";
                                                  echo wordwrap($str, 50);


                                                  Or Try it online!






                                                  share|improve this answer















                                                  PHP, 8 bytes



                                                  Admittedly not the most original solution, but PHP has a native function that matches your requirements perfectly!




                                                  wordwrap:




                                                  string wordwrap ( string $str [, int $width = 75 [, string $break = "n" [, bool $cut = FALSE ]]] )



                                                  Wraps a string to a given number of characters using a string break character.




                                                  Use like so:





                                                  $str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.";
                                                  echo wordwrap($str, 50);


                                                  Or Try it online!







                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited 2 days ago

























                                                  answered Dec 1 at 5:03









                                                  Davіd

                                                  4258




                                                  4258






















                                                      up vote
                                                      4
                                                      down vote













                                                      JavaScript (ES6),  75 73  72 bytes



                                                      Takes input as (string)(n).





                                                      s=>n=>s.split` `.map(w=>r=(u=r?r+' '+w:w)[n]?(o+=r+`
                                                      `,w):u,o=r='')&&o+r


                                                      Try it online!



                                                      Variables



                                                      The formatted output is stored in $o$ (in green below).



                                                      The updated line $u$ is defined as the concatenation of:




                                                      • the current line $r$ (in black below)

                                                      • a space if $r$ is not empty, or nothing otherwise (in orange below)

                                                      • the new word $w$ (in blue below)


                                                      We need to insert a line break whenever the $n$-th character of $u$ is set (0-indexed, in red below).



                                                      Example



                                                      $n=16$ and $s$ = "LOREM IPSUM DOLOR"



                                                      Adding "LOREM":
                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      color{blue}L&color{blue}O&color{blue}R&color{blue}E&color{blue}M&&&&&&&&&&&&\ hlineend{array}
                                                      $$



                                                      Adding "IPSUM":
                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      L&O&R&E&M&color{orange}bullet&color{blue}I&color{blue}P&color{blue}S&color{blue}U&color{blue}M&&&&&&\ hlineend{array}
                                                      $$



                                                      Adding "DOLOR":
                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      L&O&R&E&M&bullet&I&P&S&U&M&color{orange}bullet&color{blue}D&color{blue}O&color{blue}L&color{blue}O&color{blue}R\ hlineend{array}
                                                      $$



                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      color{green}L&color{green}O&color{green}R&color{green}E&color{green}M&color{green}bullet&color{green}I&color{green}P&color{green}S&color{green}U&color{green}M&color{green}hookleftarrow&&&&&\ hline
                                                      D&O&L&O&R&&&&&&&&&&&&\ hlineend{array}
                                                      $$






                                                      share|improve this answer























                                                      • Trailing spaces are allowed. maybe r+w+' '?
                                                        – l4m2
                                                        yesterday















                                                      up vote
                                                      4
                                                      down vote













                                                      JavaScript (ES6),  75 73  72 bytes



                                                      Takes input as (string)(n).





                                                      s=>n=>s.split` `.map(w=>r=(u=r?r+' '+w:w)[n]?(o+=r+`
                                                      `,w):u,o=r='')&&o+r


                                                      Try it online!



                                                      Variables



                                                      The formatted output is stored in $o$ (in green below).



                                                      The updated line $u$ is defined as the concatenation of:




                                                      • the current line $r$ (in black below)

                                                      • a space if $r$ is not empty, or nothing otherwise (in orange below)

                                                      • the new word $w$ (in blue below)


                                                      We need to insert a line break whenever the $n$-th character of $u$ is set (0-indexed, in red below).



                                                      Example



                                                      $n=16$ and $s$ = "LOREM IPSUM DOLOR"



                                                      Adding "LOREM":
                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      color{blue}L&color{blue}O&color{blue}R&color{blue}E&color{blue}M&&&&&&&&&&&&\ hlineend{array}
                                                      $$



                                                      Adding "IPSUM":
                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      L&O&R&E&M&color{orange}bullet&color{blue}I&color{blue}P&color{blue}S&color{blue}U&color{blue}M&&&&&&\ hlineend{array}
                                                      $$



                                                      Adding "DOLOR":
                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      L&O&R&E&M&bullet&I&P&S&U&M&color{orange}bullet&color{blue}D&color{blue}O&color{blue}L&color{blue}O&color{blue}R\ hlineend{array}
                                                      $$



                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      color{green}L&color{green}O&color{green}R&color{green}E&color{green}M&color{green}bullet&color{green}I&color{green}P&color{green}S&color{green}U&color{green}M&color{green}hookleftarrow&&&&&\ hline
                                                      D&O&L&O&R&&&&&&&&&&&&\ hlineend{array}
                                                      $$






                                                      share|improve this answer























                                                      • Trailing spaces are allowed. maybe r+w+' '?
                                                        – l4m2
                                                        yesterday













                                                      up vote
                                                      4
                                                      down vote










                                                      up vote
                                                      4
                                                      down vote









                                                      JavaScript (ES6),  75 73  72 bytes



                                                      Takes input as (string)(n).





                                                      s=>n=>s.split` `.map(w=>r=(u=r?r+' '+w:w)[n]?(o+=r+`
                                                      `,w):u,o=r='')&&o+r


                                                      Try it online!



                                                      Variables



                                                      The formatted output is stored in $o$ (in green below).



                                                      The updated line $u$ is defined as the concatenation of:




                                                      • the current line $r$ (in black below)

                                                      • a space if $r$ is not empty, or nothing otherwise (in orange below)

                                                      • the new word $w$ (in blue below)


                                                      We need to insert a line break whenever the $n$-th character of $u$ is set (0-indexed, in red below).



                                                      Example



                                                      $n=16$ and $s$ = "LOREM IPSUM DOLOR"



                                                      Adding "LOREM":
                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      color{blue}L&color{blue}O&color{blue}R&color{blue}E&color{blue}M&&&&&&&&&&&&\ hlineend{array}
                                                      $$



                                                      Adding "IPSUM":
                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      L&O&R&E&M&color{orange}bullet&color{blue}I&color{blue}P&color{blue}S&color{blue}U&color{blue}M&&&&&&\ hlineend{array}
                                                      $$



                                                      Adding "DOLOR":
                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      L&O&R&E&M&bullet&I&P&S&U&M&color{orange}bullet&color{blue}D&color{blue}O&color{blue}L&color{blue}O&color{blue}R\ hlineend{array}
                                                      $$



                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      color{green}L&color{green}O&color{green}R&color{green}E&color{green}M&color{green}bullet&color{green}I&color{green}P&color{green}S&color{green}U&color{green}M&color{green}hookleftarrow&&&&&\ hline
                                                      D&O&L&O&R&&&&&&&&&&&&\ hlineend{array}
                                                      $$






                                                      share|improve this answer














                                                      JavaScript (ES6),  75 73  72 bytes



                                                      Takes input as (string)(n).





                                                      s=>n=>s.split` `.map(w=>r=(u=r?r+' '+w:w)[n]?(o+=r+`
                                                      `,w):u,o=r='')&&o+r


                                                      Try it online!



                                                      Variables



                                                      The formatted output is stored in $o$ (in green below).



                                                      The updated line $u$ is defined as the concatenation of:




                                                      • the current line $r$ (in black below)

                                                      • a space if $r$ is not empty, or nothing otherwise (in orange below)

                                                      • the new word $w$ (in blue below)


                                                      We need to insert a line break whenever the $n$-th character of $u$ is set (0-indexed, in red below).



                                                      Example



                                                      $n=16$ and $s$ = "LOREM IPSUM DOLOR"



                                                      Adding "LOREM":
                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      color{blue}L&color{blue}O&color{blue}R&color{blue}E&color{blue}M&&&&&&&&&&&&\ hlineend{array}
                                                      $$



                                                      Adding "IPSUM":
                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      L&O&R&E&M&color{orange}bullet&color{blue}I&color{blue}P&color{blue}S&color{blue}U&color{blue}M&&&&&&\ hlineend{array}
                                                      $$



                                                      Adding "DOLOR":
                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      L&O&R&E&M&bullet&I&P&S&U&M&color{orange}bullet&color{blue}D&color{blue}O&color{blue}L&color{blue}O&color{blue}R\ hlineend{array}
                                                      $$



                                                      $$smallbegin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
                                                      hline
                                                      00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&color{red}{16}\ hline
                                                      color{green}L&color{green}O&color{green}R&color{green}E&color{green}M&color{green}bullet&color{green}I&color{green}P&color{green}S&color{green}U&color{green}M&color{green}hookleftarrow&&&&&\ hline
                                                      D&O&L&O&R&&&&&&&&&&&&\ hlineend{array}
                                                      $$







                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited 2 days ago

























                                                      answered Dec 1 at 1:45









                                                      Arnauld

                                                      70.3k686296




                                                      70.3k686296












                                                      • Trailing spaces are allowed. maybe r+w+' '?
                                                        – l4m2
                                                        yesterday


















                                                      • Trailing spaces are allowed. maybe r+w+' '?
                                                        – l4m2
                                                        yesterday
















                                                      Trailing spaces are allowed. maybe r+w+' '?
                                                      – l4m2
                                                      yesterday




                                                      Trailing spaces are allowed. maybe r+w+' '?
                                                      – l4m2
                                                      yesterday










                                                      up vote
                                                      4
                                                      down vote













                                                      Vim, 15 bytes/keystrokes



                                                      DJ:se tw=<C-r>"
                                                      gq_


                                                      A text formatting question? I know just the tool for the job! And it even has my name in the first two keystrokes :D



                                                      <C-r> means ctrl-r.



                                                      This could ever so slightly shorter in V, but I prefer answering in vanilla vim for answers that really show off how concise vim can be for the right challenge. And the difference is so small anyway.



                                                      This could also be the following for 15 bytes as well:



                                                      :se tw=<C-r><C-w>
                                                      ddgq_


                                                      Try it online!






                                                      share|improve this answer



















                                                      • 1




                                                        Explanation: DJ:: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]
                                                        – Erik the Outgolfer
                                                        2 days ago















                                                      up vote
                                                      4
                                                      down vote













                                                      Vim, 15 bytes/keystrokes



                                                      DJ:se tw=<C-r>"
                                                      gq_


                                                      A text formatting question? I know just the tool for the job! And it even has my name in the first two keystrokes :D



                                                      <C-r> means ctrl-r.



                                                      This could ever so slightly shorter in V, but I prefer answering in vanilla vim for answers that really show off how concise vim can be for the right challenge. And the difference is so small anyway.



                                                      This could also be the following for 15 bytes as well:



                                                      :se tw=<C-r><C-w>
                                                      ddgq_


                                                      Try it online!






                                                      share|improve this answer



















                                                      • 1




                                                        Explanation: DJ:: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]
                                                        – Erik the Outgolfer
                                                        2 days ago













                                                      up vote
                                                      4
                                                      down vote










                                                      up vote
                                                      4
                                                      down vote









                                                      Vim, 15 bytes/keystrokes



                                                      DJ:se tw=<C-r>"
                                                      gq_


                                                      A text formatting question? I know just the tool for the job! And it even has my name in the first two keystrokes :D



                                                      <C-r> means ctrl-r.



                                                      This could ever so slightly shorter in V, but I prefer answering in vanilla vim for answers that really show off how concise vim can be for the right challenge. And the difference is so small anyway.



                                                      This could also be the following for 15 bytes as well:



                                                      :se tw=<C-r><C-w>
                                                      ddgq_


                                                      Try it online!






                                                      share|improve this answer














                                                      Vim, 15 bytes/keystrokes



                                                      DJ:se tw=<C-r>"
                                                      gq_


                                                      A text formatting question? I know just the tool for the job! And it even has my name in the first two keystrokes :D



                                                      <C-r> means ctrl-r.



                                                      This could ever so slightly shorter in V, but I prefer answering in vanilla vim for answers that really show off how concise vim can be for the right challenge. And the difference is so small anyway.



                                                      This could also be the following for 15 bytes as well:



                                                      :se tw=<C-r><C-w>
                                                      ddgq_


                                                      Try it online!







                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited 2 days ago

























                                                      answered Dec 1 at 1:52









                                                      DJMcMayhem

                                                      40.7k11145307




                                                      40.7k11145307








                                                      • 1




                                                        Explanation: DJ:: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]
                                                        – Erik the Outgolfer
                                                        2 days ago














                                                      • 1




                                                        Explanation: DJ:: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]
                                                        – Erik the Outgolfer
                                                        2 days ago








                                                      1




                                                      1




                                                      Explanation: DJ:: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]
                                                      – Erik the Outgolfer
                                                      2 days ago




                                                      Explanation: DJ:: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]
                                                      – Erik the Outgolfer
                                                      2 days ago










                                                      up vote
                                                      4
                                                      down vote














                                                      Haskell, 70 bytes





                                                      s!n|length s<=n=[s]|(t,_:d)<-splitAt(until((<'!').(s!!))pred n)s=t:d!n





                                                      share|improve this answer



























                                                        up vote
                                                        4
                                                        down vote














                                                        Haskell, 70 bytes





                                                        s!n|length s<=n=[s]|(t,_:d)<-splitAt(until((<'!').(s!!))pred n)s=t:d!n





                                                        share|improve this answer

























                                                          up vote
                                                          4
                                                          down vote










                                                          up vote
                                                          4
                                                          down vote










                                                          Haskell, 70 bytes





                                                          s!n|length s<=n=[s]|(t,_:d)<-splitAt(until((<'!').(s!!))pred n)s=t:d!n





                                                          share|improve this answer















                                                          Haskell, 70 bytes





                                                          s!n|length s<=n=[s]|(t,_:d)<-splitAt(until((<'!').(s!!))pred n)s=t:d!n






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited 2 days ago

























                                                          answered 2 days ago









                                                          Lynn

                                                          49.3k794226




                                                          49.3k794226






















                                                              up vote
                                                              3
                                                              down vote














                                                              Python 2, 74 bytes





                                                              s,n=input()
                                                              while s:i=n;exec"i-=' '<(s+' '*n)[i];"*n;print s[:i];s=s[i+1:]


                                                              Try it online!






                                                              share|improve this answer

























                                                                up vote
                                                                3
                                                                down vote














                                                                Python 2, 74 bytes





                                                                s,n=input()
                                                                while s:i=n;exec"i-=' '<(s+' '*n)[i];"*n;print s[:i];s=s[i+1:]


                                                                Try it online!






                                                                share|improve this answer























                                                                  up vote
                                                                  3
                                                                  down vote










                                                                  up vote
                                                                  3
                                                                  down vote










                                                                  Python 2, 74 bytes





                                                                  s,n=input()
                                                                  while s:i=n;exec"i-=' '<(s+' '*n)[i];"*n;print s[:i];s=s[i+1:]


                                                                  Try it online!






                                                                  share|improve this answer













                                                                  Python 2, 74 bytes





                                                                  s,n=input()
                                                                  while s:i=n;exec"i-=' '<(s+' '*n)[i];"*n;print s[:i];s=s[i+1:]


                                                                  Try it online!







                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered 2 days ago









                                                                  Lynn

                                                                  49.3k794226




                                                                  49.3k794226






















                                                                      up vote
                                                                      2
                                                                      down vote














                                                                      R, 36 27 bytes



                                                                      R has this as a built-in (strwrap), we return a vector of split lines.





                                                                      function(s,n)strwrap(s,n+1)


                                                                      Try it online!






                                                                      share|improve this answer



















                                                                      • 1




                                                                        Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
                                                                        – ATMunn
                                                                        2 days ago















                                                                      up vote
                                                                      2
                                                                      down vote














                                                                      R, 36 27 bytes



                                                                      R has this as a built-in (strwrap), we return a vector of split lines.





                                                                      function(s,n)strwrap(s,n+1)


                                                                      Try it online!






                                                                      share|improve this answer



















                                                                      • 1




                                                                        Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
                                                                        – ATMunn
                                                                        2 days ago













                                                                      up vote
                                                                      2
                                                                      down vote










                                                                      up vote
                                                                      2
                                                                      down vote










                                                                      R, 36 27 bytes



                                                                      R has this as a built-in (strwrap), we return a vector of split lines.





                                                                      function(s,n)strwrap(s,n+1)


                                                                      Try it online!






                                                                      share|improve this answer















                                                                      R, 36 27 bytes



                                                                      R has this as a built-in (strwrap), we return a vector of split lines.





                                                                      function(s,n)strwrap(s,n+1)


                                                                      Try it online!







                                                                      share|improve this answer














                                                                      share|improve this answer



                                                                      share|improve this answer








                                                                      edited 2 days ago

























                                                                      answered 2 days ago









                                                                      J.Doe

                                                                      2,091112




                                                                      2,091112








                                                                      • 1




                                                                        Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
                                                                        – ATMunn
                                                                        2 days ago














                                                                      • 1




                                                                        Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
                                                                        – ATMunn
                                                                        2 days ago








                                                                      1




                                                                      1




                                                                      Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
                                                                      – ATMunn
                                                                      2 days ago




                                                                      Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
                                                                      – ATMunn
                                                                      2 days ago










                                                                      up vote
                                                                      1
                                                                      down vote














                                                                      Retina 0.8.2, 37 bytes



                                                                      .+$
                                                                      $*
                                                                      !`(?=S.*¶(1)+)(?<-1>.)+(?=s)


                                                                      Try it online! Takes s and n on separate lines. Explanation:



                                                                      .+$
                                                                      $*


                                                                      Convert n to unary.



                                                                      (?=S.*¶(1)+)(?<-1>.)+(?=s)


                                                                      Match non-whitespace, then look ahead to n and count it as $#1. Then go back and use a balancing group to match up to n characters followed by whitespace.



                                                                      !`


                                                                      Output the matches as a list of lines.






                                                                      share|improve this answer

























                                                                        up vote
                                                                        1
                                                                        down vote














                                                                        Retina 0.8.2, 37 bytes



                                                                        .+$
                                                                        $*
                                                                        !`(?=S.*¶(1)+)(?<-1>.)+(?=s)


                                                                        Try it online! Takes s and n on separate lines. Explanation:



                                                                        .+$
                                                                        $*


                                                                        Convert n to unary.



                                                                        (?=S.*¶(1)+)(?<-1>.)+(?=s)


                                                                        Match non-whitespace, then look ahead to n and count it as $#1. Then go back and use a balancing group to match up to n characters followed by whitespace.



                                                                        !`


                                                                        Output the matches as a list of lines.






                                                                        share|improve this answer























                                                                          up vote
                                                                          1
                                                                          down vote










                                                                          up vote
                                                                          1
                                                                          down vote










                                                                          Retina 0.8.2, 37 bytes



                                                                          .+$
                                                                          $*
                                                                          !`(?=S.*¶(1)+)(?<-1>.)+(?=s)


                                                                          Try it online! Takes s and n on separate lines. Explanation:



                                                                          .+$
                                                                          $*


                                                                          Convert n to unary.



                                                                          (?=S.*¶(1)+)(?<-1>.)+(?=s)


                                                                          Match non-whitespace, then look ahead to n and count it as $#1. Then go back and use a balancing group to match up to n characters followed by whitespace.



                                                                          !`


                                                                          Output the matches as a list of lines.






                                                                          share|improve this answer













                                                                          Retina 0.8.2, 37 bytes



                                                                          .+$
                                                                          $*
                                                                          !`(?=S.*¶(1)+)(?<-1>.)+(?=s)


                                                                          Try it online! Takes s and n on separate lines. Explanation:



                                                                          .+$
                                                                          $*


                                                                          Convert n to unary.



                                                                          (?=S.*¶(1)+)(?<-1>.)+(?=s)


                                                                          Match non-whitespace, then look ahead to n and count it as $#1. Then go back and use a balancing group to match up to n characters followed by whitespace.



                                                                          !`


                                                                          Output the matches as a list of lines.







                                                                          share|improve this answer












                                                                          share|improve this answer



                                                                          share|improve this answer










                                                                          answered 2 days ago









                                                                          Neil

                                                                          78.5k744175




                                                                          78.5k744175






















                                                                              up vote
                                                                              1
                                                                              down vote














                                                                              Charcoal, 19 bytes



                                                                              Nθ←F⪪S «¿‹⁺LιⅈθM→⸿ι


                                                                              Try it online! Link is to verbose version of code. Takes input of n and s on separate lines. Explanation:



                                                                              Nθ


                                                                              Input n.






                                                                              Move the cursor left one square to balance the right movement from the first iteration of the loop.



                                                                              F⪪S «


                                                                              Split the string on spaces and loop over the words.



                                                                              ¿‹⁺Lιⅈθ


                                                                              Calculate whether the next word will reach the right edge.



                                                                              M→


                                                                              If it will not then move one square right.



                                                                              ⸿


                                                                              If it will then start a new line.



                                                                              ι


                                                                              Output the word.






                                                                              share|improve this answer

























                                                                                up vote
                                                                                1
                                                                                down vote














                                                                                Charcoal, 19 bytes



                                                                                Nθ←F⪪S «¿‹⁺LιⅈθM→⸿ι


                                                                                Try it online! Link is to verbose version of code. Takes input of n and s on separate lines. Explanation:



                                                                                Nθ


                                                                                Input n.






                                                                                Move the cursor left one square to balance the right movement from the first iteration of the loop.



                                                                                F⪪S «


                                                                                Split the string on spaces and loop over the words.



                                                                                ¿‹⁺Lιⅈθ


                                                                                Calculate whether the next word will reach the right edge.



                                                                                M→


                                                                                If it will not then move one square right.



                                                                                ⸿


                                                                                If it will then start a new line.



                                                                                ι


                                                                                Output the word.






                                                                                share|improve this answer























                                                                                  up vote
                                                                                  1
                                                                                  down vote










                                                                                  up vote
                                                                                  1
                                                                                  down vote










                                                                                  Charcoal, 19 bytes



                                                                                  Nθ←F⪪S «¿‹⁺LιⅈθM→⸿ι


                                                                                  Try it online! Link is to verbose version of code. Takes input of n and s on separate lines. Explanation:



                                                                                  Nθ


                                                                                  Input n.






                                                                                  Move the cursor left one square to balance the right movement from the first iteration of the loop.



                                                                                  F⪪S «


                                                                                  Split the string on spaces and loop over the words.



                                                                                  ¿‹⁺Lιⅈθ


                                                                                  Calculate whether the next word will reach the right edge.



                                                                                  M→


                                                                                  If it will not then move one square right.



                                                                                  ⸿


                                                                                  If it will then start a new line.



                                                                                  ι


                                                                                  Output the word.






                                                                                  share|improve this answer













                                                                                  Charcoal, 19 bytes



                                                                                  Nθ←F⪪S «¿‹⁺LιⅈθM→⸿ι


                                                                                  Try it online! Link is to verbose version of code. Takes input of n and s on separate lines. Explanation:



                                                                                  Nθ


                                                                                  Input n.






                                                                                  Move the cursor left one square to balance the right movement from the first iteration of the loop.



                                                                                  F⪪S «


                                                                                  Split the string on spaces and loop over the words.



                                                                                  ¿‹⁺Lιⅈθ


                                                                                  Calculate whether the next word will reach the right edge.



                                                                                  M→


                                                                                  If it will not then move one square right.



                                                                                  ⸿


                                                                                  If it will then start a new line.



                                                                                  ι


                                                                                  Output the word.







                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered 2 days ago









                                                                                  Neil

                                                                                  78.5k744175




                                                                                  78.5k744175






















                                                                                      up vote
                                                                                      1
                                                                                      down vote














                                                                                      Red, 125, 117, 114 112 bytes



                                                                                      func[s n][d: 0 parse s[any[to" "p:" "opt[[to" "| to end]q:(if(-1 - d + index? q)> n[p/1: #"^/"d: index? p])]]]s]


                                                                                      Try it online!






                                                                                      share|improve this answer



























                                                                                        up vote
                                                                                        1
                                                                                        down vote














                                                                                        Red, 125, 117, 114 112 bytes



                                                                                        func[s n][d: 0 parse s[any[to" "p:" "opt[[to" "| to end]q:(if(-1 - d + index? q)> n[p/1: #"^/"d: index? p])]]]s]


                                                                                        Try it online!






                                                                                        share|improve this answer

























                                                                                          up vote
                                                                                          1
                                                                                          down vote










                                                                                          up vote
                                                                                          1
                                                                                          down vote










                                                                                          Red, 125, 117, 114 112 bytes



                                                                                          func[s n][d: 0 parse s[any[to" "p:" "opt[[to" "| to end]q:(if(-1 - d + index? q)> n[p/1: #"^/"d: index? p])]]]s]


                                                                                          Try it online!






                                                                                          share|improve this answer















                                                                                          Red, 125, 117, 114 112 bytes



                                                                                          func[s n][d: 0 parse s[any[to" "p:" "opt[[to" "| to end]q:(if(-1 - d + index? q)> n[p/1: #"^/"d: index? p])]]]s]


                                                                                          Try it online!







                                                                                          share|improve this answer














                                                                                          share|improve this answer



                                                                                          share|improve this answer








                                                                                          edited yesterday

























                                                                                          answered 2 days ago









                                                                                          Galen Ivanov

                                                                                          6,01211032




                                                                                          6,01211032






















                                                                                              up vote
                                                                                              1
                                                                                              down vote













                                                                                              JavaScript, 39 bytes





                                                                                              s=>n=>eval(`s.match(/.{1,${n}} |.+/g)`)


                                                                                              Try it online!






                                                                                              share|improve this answer























                                                                                              • Fail at the end
                                                                                                – l4m2
                                                                                                yesterday










                                                                                              • @l4m2 fixed....
                                                                                                – tsh
                                                                                                yesterday















                                                                                              up vote
                                                                                              1
                                                                                              down vote













                                                                                              JavaScript, 39 bytes





                                                                                              s=>n=>eval(`s.match(/.{1,${n}} |.+/g)`)


                                                                                              Try it online!






                                                                                              share|improve this answer























                                                                                              • Fail at the end
                                                                                                – l4m2
                                                                                                yesterday










                                                                                              • @l4m2 fixed....
                                                                                                – tsh
                                                                                                yesterday













                                                                                              up vote
                                                                                              1
                                                                                              down vote










                                                                                              up vote
                                                                                              1
                                                                                              down vote









                                                                                              JavaScript, 39 bytes





                                                                                              s=>n=>eval(`s.match(/.{1,${n}} |.+/g)`)


                                                                                              Try it online!






                                                                                              share|improve this answer














                                                                                              JavaScript, 39 bytes





                                                                                              s=>n=>eval(`s.match(/.{1,${n}} |.+/g)`)


                                                                                              Try it online!







                                                                                              share|improve this answer














                                                                                              share|improve this answer



                                                                                              share|improve this answer








                                                                                              edited yesterday

























                                                                                              answered yesterday









                                                                                              tsh

                                                                                              8,10011446




                                                                                              8,10011446












                                                                                              • Fail at the end
                                                                                                – l4m2
                                                                                                yesterday










                                                                                              • @l4m2 fixed....
                                                                                                – tsh
                                                                                                yesterday


















                                                                                              • Fail at the end
                                                                                                – l4m2
                                                                                                yesterday










                                                                                              • @l4m2 fixed....
                                                                                                – tsh
                                                                                                yesterday
















                                                                                              Fail at the end
                                                                                              – l4m2
                                                                                              yesterday




                                                                                              Fail at the end
                                                                                              – l4m2
                                                                                              yesterday












                                                                                              @l4m2 fixed....
                                                                                              – tsh
                                                                                              yesterday




                                                                                              @l4m2 fixed....
                                                                                              – tsh
                                                                                              yesterday










                                                                                              up vote
                                                                                              1
                                                                                              down vote













                                                                                              Powershell, 40 83 bytes



                                                                                              Test case with n=80 added.





                                                                                              param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
                                                                                              $o


                                                                                              Test script:



                                                                                              $f = {

                                                                                              param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
                                                                                              $o

                                                                                              }

                                                                                              @(
                                                                                              ,(50, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
                                                                                              "Lorem ipsum dolor sit amet, consectetur adipiscing",
                                                                                              "elit. Sed eget erat lectus. Morbi mi mi, fringilla",
                                                                                              "sed suscipit ullamcorper, tristique at mauris.",
                                                                                              "Morbi non commodo nibh. Pellentesque habitant",
                                                                                              "morbi tristique senectus et netus et malesuada",
                                                                                              "fames ac turpis egestas. Sed at iaculis mauris.",
                                                                                              "Praesent a sem augue. Nulla lectus sapien, auctor",
                                                                                              "nec pharetra eu, tincidunt ac diam. Sed ligula",
                                                                                              "arcu, aliquam quis velit aliquam, dictum varius",
                                                                                              "erat.")
                                                                                              ,(80, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
                                                                                              "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus.",
                                                                                              "Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non",
                                                                                              "commodo nibh. Pellentesque habitant morbi tristique senectus et netus et",
                                                                                              "malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue.",
                                                                                              "Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu,",
                                                                                              "aliquam quis velit aliquam, dictum varius erat.")
                                                                                              ) | %{
                                                                                              $n,$s,$expected = $_
                                                                                              $result = &$f $s $n
                                                                                              "$result"-eq"$expected"
                                                                                              # $result # uncomment this line to dispaly a result
                                                                                              }


                                                                                              Output:



                                                                                              True
                                                                                              True





                                                                                              share|improve this answer



























                                                                                                up vote
                                                                                                1
                                                                                                down vote













                                                                                                Powershell, 40 83 bytes



                                                                                                Test case with n=80 added.





                                                                                                param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
                                                                                                $o


                                                                                                Test script:



                                                                                                $f = {

                                                                                                param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
                                                                                                $o

                                                                                                }

                                                                                                @(
                                                                                                ,(50, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
                                                                                                "Lorem ipsum dolor sit amet, consectetur adipiscing",
                                                                                                "elit. Sed eget erat lectus. Morbi mi mi, fringilla",
                                                                                                "sed suscipit ullamcorper, tristique at mauris.",
                                                                                                "Morbi non commodo nibh. Pellentesque habitant",
                                                                                                "morbi tristique senectus et netus et malesuada",
                                                                                                "fames ac turpis egestas. Sed at iaculis mauris.",
                                                                                                "Praesent a sem augue. Nulla lectus sapien, auctor",
                                                                                                "nec pharetra eu, tincidunt ac diam. Sed ligula",
                                                                                                "arcu, aliquam quis velit aliquam, dictum varius",
                                                                                                "erat.")
                                                                                                ,(80, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
                                                                                                "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus.",
                                                                                                "Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non",
                                                                                                "commodo nibh. Pellentesque habitant morbi tristique senectus et netus et",
                                                                                                "malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue.",
                                                                                                "Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu,",
                                                                                                "aliquam quis velit aliquam, dictum varius erat.")
                                                                                                ) | %{
                                                                                                $n,$s,$expected = $_
                                                                                                $result = &$f $s $n
                                                                                                "$result"-eq"$expected"
                                                                                                # $result # uncomment this line to dispaly a result
                                                                                                }


                                                                                                Output:



                                                                                                True
                                                                                                True





                                                                                                share|improve this answer

























                                                                                                  up vote
                                                                                                  1
                                                                                                  down vote










                                                                                                  up vote
                                                                                                  1
                                                                                                  down vote









                                                                                                  Powershell, 40 83 bytes



                                                                                                  Test case with n=80 added.





                                                                                                  param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
                                                                                                  $o


                                                                                                  Test script:



                                                                                                  $f = {

                                                                                                  param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
                                                                                                  $o

                                                                                                  }

                                                                                                  @(
                                                                                                  ,(50, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
                                                                                                  "Lorem ipsum dolor sit amet, consectetur adipiscing",
                                                                                                  "elit. Sed eget erat lectus. Morbi mi mi, fringilla",
                                                                                                  "sed suscipit ullamcorper, tristique at mauris.",
                                                                                                  "Morbi non commodo nibh. Pellentesque habitant",
                                                                                                  "morbi tristique senectus et netus et malesuada",
                                                                                                  "fames ac turpis egestas. Sed at iaculis mauris.",
                                                                                                  "Praesent a sem augue. Nulla lectus sapien, auctor",
                                                                                                  "nec pharetra eu, tincidunt ac diam. Sed ligula",
                                                                                                  "arcu, aliquam quis velit aliquam, dictum varius",
                                                                                                  "erat.")
                                                                                                  ,(80, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
                                                                                                  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus.",
                                                                                                  "Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non",
                                                                                                  "commodo nibh. Pellentesque habitant morbi tristique senectus et netus et",
                                                                                                  "malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue.",
                                                                                                  "Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu,",
                                                                                                  "aliquam quis velit aliquam, dictum varius erat.")
                                                                                                  ) | %{
                                                                                                  $n,$s,$expected = $_
                                                                                                  $result = &$f $s $n
                                                                                                  "$result"-eq"$expected"
                                                                                                  # $result # uncomment this line to dispaly a result
                                                                                                  }


                                                                                                  Output:



                                                                                                  True
                                                                                                  True





                                                                                                  share|improve this answer














                                                                                                  Powershell, 40 83 bytes



                                                                                                  Test case with n=80 added.





                                                                                                  param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
                                                                                                  $o


                                                                                                  Test script:



                                                                                                  $f = {

                                                                                                  param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
                                                                                                  $o

                                                                                                  }

                                                                                                  @(
                                                                                                  ,(50, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
                                                                                                  "Lorem ipsum dolor sit amet, consectetur adipiscing",
                                                                                                  "elit. Sed eget erat lectus. Morbi mi mi, fringilla",
                                                                                                  "sed suscipit ullamcorper, tristique at mauris.",
                                                                                                  "Morbi non commodo nibh. Pellentesque habitant",
                                                                                                  "morbi tristique senectus et netus et malesuada",
                                                                                                  "fames ac turpis egestas. Sed at iaculis mauris.",
                                                                                                  "Praesent a sem augue. Nulla lectus sapien, auctor",
                                                                                                  "nec pharetra eu, tincidunt ac diam. Sed ligula",
                                                                                                  "arcu, aliquam quis velit aliquam, dictum varius",
                                                                                                  "erat.")
                                                                                                  ,(80, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
                                                                                                  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus.",
                                                                                                  "Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non",
                                                                                                  "commodo nibh. Pellentesque habitant morbi tristique senectus et netus et",
                                                                                                  "malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue.",
                                                                                                  "Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu,",
                                                                                                  "aliquam quis velit aliquam, dictum varius erat.")
                                                                                                  ) | %{
                                                                                                  $n,$s,$expected = $_
                                                                                                  $result = &$f $s $n
                                                                                                  "$result"-eq"$expected"
                                                                                                  # $result # uncomment this line to dispaly a result
                                                                                                  }


                                                                                                  Output:



                                                                                                  True
                                                                                                  True






                                                                                                  share|improve this answer














                                                                                                  share|improve this answer



                                                                                                  share|improve this answer








                                                                                                  edited 16 hours ago

























                                                                                                  answered yesterday









                                                                                                  mazzy

                                                                                                  1,867313




                                                                                                  1,867313






















                                                                                                      up vote
                                                                                                      1
                                                                                                      down vote














                                                                                                      Japt, 24 bytes



                                                                                                      ¸r@[XY]q(X·Ì+S+Y Ê>V?R:S


                                                                                                      Try it online!



                                                                                                      Thanks to Bubbler for removing some duplication.



                                                                                                      Explanation:



                                                                                                      ¸                           :Split into words
                                                                                                      r@ :Reduce back into a string by:
                                                                                                      X : Start with the already reduced portion
                                                                                                      ·Ì : Get the last line
                                                                                                      +S+Y : Add a space and the next word
                                                                                                      Ê>V? : If the length of that line is greater than n:
                                                                                                      R : Choose newline
                                                                                                      : : Otherwise:
                                                                                                      S : Choose space
                                                                                                      [XY]q( : Join the next word to the result using the chosen character





                                                                                                      share|improve this answer























                                                                                                      • 24 bytes with [X,Y].join(...).
                                                                                                        – Bubbler
                                                                                                        yesterday















                                                                                                      up vote
                                                                                                      1
                                                                                                      down vote














                                                                                                      Japt, 24 bytes



                                                                                                      ¸r@[XY]q(X·Ì+S+Y Ê>V?R:S


                                                                                                      Try it online!



                                                                                                      Thanks to Bubbler for removing some duplication.



                                                                                                      Explanation:



                                                                                                      ¸                           :Split into words
                                                                                                      r@ :Reduce back into a string by:
                                                                                                      X : Start with the already reduced portion
                                                                                                      ·Ì : Get the last line
                                                                                                      +S+Y : Add a space and the next word
                                                                                                      Ê>V? : If the length of that line is greater than n:
                                                                                                      R : Choose newline
                                                                                                      : : Otherwise:
                                                                                                      S : Choose space
                                                                                                      [XY]q( : Join the next word to the result using the chosen character





                                                                                                      share|improve this answer























                                                                                                      • 24 bytes with [X,Y].join(...).
                                                                                                        – Bubbler
                                                                                                        yesterday













                                                                                                      up vote
                                                                                                      1
                                                                                                      down vote










                                                                                                      up vote
                                                                                                      1
                                                                                                      down vote










                                                                                                      Japt, 24 bytes



                                                                                                      ¸r@[XY]q(X·Ì+S+Y Ê>V?R:S


                                                                                                      Try it online!



                                                                                                      Thanks to Bubbler for removing some duplication.



                                                                                                      Explanation:



                                                                                                      ¸                           :Split into words
                                                                                                      r@ :Reduce back into a string by:
                                                                                                      X : Start with the already reduced portion
                                                                                                      ·Ì : Get the last line
                                                                                                      +S+Y : Add a space and the next word
                                                                                                      Ê>V? : If the length of that line is greater than n:
                                                                                                      R : Choose newline
                                                                                                      : : Otherwise:
                                                                                                      S : Choose space
                                                                                                      [XY]q( : Join the next word to the result using the chosen character





                                                                                                      share|improve this answer















                                                                                                      Japt, 24 bytes



                                                                                                      ¸r@[XY]q(X·Ì+S+Y Ê>V?R:S


                                                                                                      Try it online!



                                                                                                      Thanks to Bubbler for removing some duplication.



                                                                                                      Explanation:



                                                                                                      ¸                           :Split into words
                                                                                                      r@ :Reduce back into a string by:
                                                                                                      X : Start with the already reduced portion
                                                                                                      ·Ì : Get the last line
                                                                                                      +S+Y : Add a space and the next word
                                                                                                      Ê>V? : If the length of that line is greater than n:
                                                                                                      R : Choose newline
                                                                                                      : : Otherwise:
                                                                                                      S : Choose space
                                                                                                      [XY]q( : Join the next word to the result using the chosen character






                                                                                                      share|improve this answer














                                                                                                      share|improve this answer



                                                                                                      share|improve this answer








                                                                                                      edited 14 hours ago

























                                                                                                      answered 2 days ago









                                                                                                      Kamil Drakari

                                                                                                      2,646416




                                                                                                      2,646416












                                                                                                      • 24 bytes with [X,Y].join(...).
                                                                                                        – Bubbler
                                                                                                        yesterday


















                                                                                                      • 24 bytes with [X,Y].join(...).
                                                                                                        – Bubbler
                                                                                                        yesterday
















                                                                                                      24 bytes with [X,Y].join(...).
                                                                                                      – Bubbler
                                                                                                      yesterday




                                                                                                      24 bytes with [X,Y].join(...).
                                                                                                      – Bubbler
                                                                                                      yesterday










                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote













                                                                                                      Bash/Coreutils, 8 bytes



                                                                                                      fold -sw <n>


                                                                                                      Try It Online!



                                                                                                      The fold utility, that's bundled along with coreutils, does exactly what the question asks. The -s flag makes it so that it only breaks on whitespaces(ie. when the word ends), the value of n is passed using the argument -w. Input is accepted via stdin






                                                                                                      share|improve this answer























                                                                                                      • Unfortunately, that doesn't work for the test case from the question, because fold counts a trailing space as one of the 50 bytes.
                                                                                                        – Dennis
                                                                                                        2 days ago










                                                                                                      • On a side note, only full programs and functions are allowed by default. fold -sw$1 (or fold -s$1) would comply with that rule.
                                                                                                        – Dennis
                                                                                                        2 days ago















                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote













                                                                                                      Bash/Coreutils, 8 bytes



                                                                                                      fold -sw <n>


                                                                                                      Try It Online!



                                                                                                      The fold utility, that's bundled along with coreutils, does exactly what the question asks. The -s flag makes it so that it only breaks on whitespaces(ie. when the word ends), the value of n is passed using the argument -w. Input is accepted via stdin






                                                                                                      share|improve this answer























                                                                                                      • Unfortunately, that doesn't work for the test case from the question, because fold counts a trailing space as one of the 50 bytes.
                                                                                                        – Dennis
                                                                                                        2 days ago










                                                                                                      • On a side note, only full programs and functions are allowed by default. fold -sw$1 (or fold -s$1) would comply with that rule.
                                                                                                        – Dennis
                                                                                                        2 days ago













                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote










                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote









                                                                                                      Bash/Coreutils, 8 bytes



                                                                                                      fold -sw <n>


                                                                                                      Try It Online!



                                                                                                      The fold utility, that's bundled along with coreutils, does exactly what the question asks. The -s flag makes it so that it only breaks on whitespaces(ie. when the word ends), the value of n is passed using the argument -w. Input is accepted via stdin






                                                                                                      share|improve this answer














                                                                                                      Bash/Coreutils, 8 bytes



                                                                                                      fold -sw <n>


                                                                                                      Try It Online!



                                                                                                      The fold utility, that's bundled along with coreutils, does exactly what the question asks. The -s flag makes it so that it only breaks on whitespaces(ie. when the word ends), the value of n is passed using the argument -w. Input is accepted via stdin







                                                                                                      share|improve this answer














                                                                                                      share|improve this answer



                                                                                                      share|improve this answer








                                                                                                      edited 2 days ago

























                                                                                                      answered 2 days ago









                                                                                                      Amith KK

                                                                                                      18017




                                                                                                      18017












                                                                                                      • Unfortunately, that doesn't work for the test case from the question, because fold counts a trailing space as one of the 50 bytes.
                                                                                                        – Dennis
                                                                                                        2 days ago










                                                                                                      • On a side note, only full programs and functions are allowed by default. fold -sw$1 (or fold -s$1) would comply with that rule.
                                                                                                        – Dennis
                                                                                                        2 days ago


















                                                                                                      • Unfortunately, that doesn't work for the test case from the question, because fold counts a trailing space as one of the 50 bytes.
                                                                                                        – Dennis
                                                                                                        2 days ago










                                                                                                      • On a side note, only full programs and functions are allowed by default. fold -sw$1 (or fold -s$1) would comply with that rule.
                                                                                                        – Dennis
                                                                                                        2 days ago
















                                                                                                      Unfortunately, that doesn't work for the test case from the question, because fold counts a trailing space as one of the 50 bytes.
                                                                                                      – Dennis
                                                                                                      2 days ago




                                                                                                      Unfortunately, that doesn't work for the test case from the question, because fold counts a trailing space as one of the 50 bytes.
                                                                                                      – Dennis
                                                                                                      2 days ago












                                                                                                      On a side note, only full programs and functions are allowed by default. fold -sw$1 (or fold -s$1) would comply with that rule.
                                                                                                      – Dennis
                                                                                                      2 days ago




                                                                                                      On a side note, only full programs and functions are allowed by default. fold -sw$1 (or fold -s$1) would comply with that rule.
                                                                                                      – Dennis
                                                                                                      2 days ago










                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote













                                                                                                      Thanks to @Erik the Outgolfer, a golfed version :




                                                                                                      Python 3, 94 bytes





                                                                                                      def f(t,n):
                                                                                                      while t:i=n+(t[min(len(t)-1,n)]==" "or-t[n-1::-1].find(' '));print(t[:i]);t=t[i:]


                                                                                                      Try it online!



                                                                                                      # Python 3, 130 bytes





                                                                                                      def f(t,n):
                                                                                                      l=
                                                                                                      while len(t):
                                                                                                      i=(n-t[:n][::-1].find(' '),n+1)[t[min(len(t)-1,n)]==" "]
                                                                                                      l.append(t[:i])
                                                                                                      t=t[i::]
                                                                                                      return l


                                                                                                      Try it online!



                                                                                                      Not so golfed version...






                                                                                                      share|improve this answer



















                                                                                                      • 1




                                                                                                        Some golfs. (prints to STDOUT, doesn't return).
                                                                                                        – Erik the Outgolfer
                                                                                                        2 days ago















                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote













                                                                                                      Thanks to @Erik the Outgolfer, a golfed version :




                                                                                                      Python 3, 94 bytes





                                                                                                      def f(t,n):
                                                                                                      while t:i=n+(t[min(len(t)-1,n)]==" "or-t[n-1::-1].find(' '));print(t[:i]);t=t[i:]


                                                                                                      Try it online!



                                                                                                      # Python 3, 130 bytes





                                                                                                      def f(t,n):
                                                                                                      l=
                                                                                                      while len(t):
                                                                                                      i=(n-t[:n][::-1].find(' '),n+1)[t[min(len(t)-1,n)]==" "]
                                                                                                      l.append(t[:i])
                                                                                                      t=t[i::]
                                                                                                      return l


                                                                                                      Try it online!



                                                                                                      Not so golfed version...






                                                                                                      share|improve this answer



















                                                                                                      • 1




                                                                                                        Some golfs. (prints to STDOUT, doesn't return).
                                                                                                        – Erik the Outgolfer
                                                                                                        2 days ago













                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote










                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote









                                                                                                      Thanks to @Erik the Outgolfer, a golfed version :




                                                                                                      Python 3, 94 bytes





                                                                                                      def f(t,n):
                                                                                                      while t:i=n+(t[min(len(t)-1,n)]==" "or-t[n-1::-1].find(' '));print(t[:i]);t=t[i:]


                                                                                                      Try it online!



                                                                                                      # Python 3, 130 bytes





                                                                                                      def f(t,n):
                                                                                                      l=
                                                                                                      while len(t):
                                                                                                      i=(n-t[:n][::-1].find(' '),n+1)[t[min(len(t)-1,n)]==" "]
                                                                                                      l.append(t[:i])
                                                                                                      t=t[i::]
                                                                                                      return l


                                                                                                      Try it online!



                                                                                                      Not so golfed version...






                                                                                                      share|improve this answer














                                                                                                      Thanks to @Erik the Outgolfer, a golfed version :




                                                                                                      Python 3, 94 bytes





                                                                                                      def f(t,n):
                                                                                                      while t:i=n+(t[min(len(t)-1,n)]==" "or-t[n-1::-1].find(' '));print(t[:i]);t=t[i:]


                                                                                                      Try it online!



                                                                                                      # Python 3, 130 bytes





                                                                                                      def f(t,n):
                                                                                                      l=
                                                                                                      while len(t):
                                                                                                      i=(n-t[:n][::-1].find(' '),n+1)[t[min(len(t)-1,n)]==" "]
                                                                                                      l.append(t[:i])
                                                                                                      t=t[i::]
                                                                                                      return l


                                                                                                      Try it online!



                                                                                                      Not so golfed version...







                                                                                                      share|improve this answer














                                                                                                      share|improve this answer



                                                                                                      share|improve this answer








                                                                                                      edited 2 days ago

























                                                                                                      answered 2 days ago









                                                                                                      david

                                                                                                      647




                                                                                                      647








                                                                                                      • 1




                                                                                                        Some golfs. (prints to STDOUT, doesn't return).
                                                                                                        – Erik the Outgolfer
                                                                                                        2 days ago














                                                                                                      • 1




                                                                                                        Some golfs. (prints to STDOUT, doesn't return).
                                                                                                        – Erik the Outgolfer
                                                                                                        2 days ago








                                                                                                      1




                                                                                                      1




                                                                                                      Some golfs. (prints to STDOUT, doesn't return).
                                                                                                      – Erik the Outgolfer
                                                                                                      2 days ago




                                                                                                      Some golfs. (prints to STDOUT, doesn't return).
                                                                                                      – Erik the Outgolfer
                                                                                                      2 days ago










                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote













                                                                                                      JavaScript + HTML + CSS, 117 64 bytes



                                                                                                      -53 bytes courtesy of @Neil






                                                                                                      n=50
                                                                                                      s="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
                                                                                                      f=(n,s)=>document.body.innerHTML+=`<tt><p style=width:${n}ch>${s}`
                                                                                                      f(n,s)








                                                                                                      share|improve this answer



















                                                                                                      • 1




                                                                                                        At least in my browser you can cut this down to (n,s)=>document.body.innerHTML+=`<p style=width:${n}ch><tt>${s}</tt></p>` for 74 bytes. If you're willing to dig out old versions of Firefox you can save another 8 bytes with (n,s)=>document.body.innerHTML+=`<pre wrap width=${n}>${s}</pre>` .
                                                                                                        – Neil
                                                                                                        2 days ago










                                                                                                      • @Neil Nice use of ch units. Firefox 65 computes 50ch as 500px; Chromium 70 computes 50ch as 400px
                                                                                                        – guest271314
                                                                                                        2 days ago










                                                                                                      • This answer is wrong. elit. Sed eget erat lectus. Morbi mi mi, fringilla sed (2nd line) is more than 50 characters. I'm using the newest Chrome.
                                                                                                        – mbomb007
                                                                                                        2 days ago












                                                                                                      • I was able to tweak my original suggestion to work in Chrome by putting the <p> inside the <tt>.
                                                                                                        – Neil
                                                                                                        2 days ago






                                                                                                      • 1




                                                                                                        next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
                                                                                                        – Neil
                                                                                                        2 days ago















                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote













                                                                                                      JavaScript + HTML + CSS, 117 64 bytes



                                                                                                      -53 bytes courtesy of @Neil






                                                                                                      n=50
                                                                                                      s="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
                                                                                                      f=(n,s)=>document.body.innerHTML+=`<tt><p style=width:${n}ch>${s}`
                                                                                                      f(n,s)








                                                                                                      share|improve this answer



















                                                                                                      • 1




                                                                                                        At least in my browser you can cut this down to (n,s)=>document.body.innerHTML+=`<p style=width:${n}ch><tt>${s}</tt></p>` for 74 bytes. If you're willing to dig out old versions of Firefox you can save another 8 bytes with (n,s)=>document.body.innerHTML+=`<pre wrap width=${n}>${s}</pre>` .
                                                                                                        – Neil
                                                                                                        2 days ago










                                                                                                      • @Neil Nice use of ch units. Firefox 65 computes 50ch as 500px; Chromium 70 computes 50ch as 400px
                                                                                                        – guest271314
                                                                                                        2 days ago










                                                                                                      • This answer is wrong. elit. Sed eget erat lectus. Morbi mi mi, fringilla sed (2nd line) is more than 50 characters. I'm using the newest Chrome.
                                                                                                        – mbomb007
                                                                                                        2 days ago












                                                                                                      • I was able to tweak my original suggestion to work in Chrome by putting the <p> inside the <tt>.
                                                                                                        – Neil
                                                                                                        2 days ago






                                                                                                      • 1




                                                                                                        next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
                                                                                                        – Neil
                                                                                                        2 days ago













                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote










                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote









                                                                                                      JavaScript + HTML + CSS, 117 64 bytes



                                                                                                      -53 bytes courtesy of @Neil






                                                                                                      n=50
                                                                                                      s="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
                                                                                                      f=(n,s)=>document.body.innerHTML+=`<tt><p style=width:${n}ch>${s}`
                                                                                                      f(n,s)








                                                                                                      share|improve this answer














                                                                                                      JavaScript + HTML + CSS, 117 64 bytes



                                                                                                      -53 bytes courtesy of @Neil






                                                                                                      n=50
                                                                                                      s="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
                                                                                                      f=(n,s)=>document.body.innerHTML+=`<tt><p style=width:${n}ch>${s}`
                                                                                                      f(n,s)








                                                                                                      n=50
                                                                                                      s="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
                                                                                                      f=(n,s)=>document.body.innerHTML+=`<tt><p style=width:${n}ch>${s}`
                                                                                                      f(n,s)





                                                                                                      n=50
                                                                                                      s="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
                                                                                                      f=(n,s)=>document.body.innerHTML+=`<tt><p style=width:${n}ch>${s}`
                                                                                                      f(n,s)






                                                                                                      share|improve this answer














                                                                                                      share|improve this answer



                                                                                                      share|improve this answer








                                                                                                      edited 2 days ago

























                                                                                                      answered Dec 1 at 2:17









                                                                                                      guest271314

                                                                                                      317211




                                                                                                      317211








                                                                                                      • 1




                                                                                                        At least in my browser you can cut this down to (n,s)=>document.body.innerHTML+=`<p style=width:${n}ch><tt>${s}</tt></p>` for 74 bytes. If you're willing to dig out old versions of Firefox you can save another 8 bytes with (n,s)=>document.body.innerHTML+=`<pre wrap width=${n}>${s}</pre>` .
                                                                                                        – Neil
                                                                                                        2 days ago










                                                                                                      • @Neil Nice use of ch units. Firefox 65 computes 50ch as 500px; Chromium 70 computes 50ch as 400px
                                                                                                        – guest271314
                                                                                                        2 days ago










                                                                                                      • This answer is wrong. elit. Sed eget erat lectus. Morbi mi mi, fringilla sed (2nd line) is more than 50 characters. I'm using the newest Chrome.
                                                                                                        – mbomb007
                                                                                                        2 days ago












                                                                                                      • I was able to tweak my original suggestion to work in Chrome by putting the <p> inside the <tt>.
                                                                                                        – Neil
                                                                                                        2 days ago






                                                                                                      • 1




                                                                                                        next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
                                                                                                        – Neil
                                                                                                        2 days ago














                                                                                                      • 1




                                                                                                        At least in my browser you can cut this down to (n,s)=>document.body.innerHTML+=`<p style=width:${n}ch><tt>${s}</tt></p>` for 74 bytes. If you're willing to dig out old versions of Firefox you can save another 8 bytes with (n,s)=>document.body.innerHTML+=`<pre wrap width=${n}>${s}</pre>` .
                                                                                                        – Neil
                                                                                                        2 days ago










                                                                                                      • @Neil Nice use of ch units. Firefox 65 computes 50ch as 500px; Chromium 70 computes 50ch as 400px
                                                                                                        – guest271314
                                                                                                        2 days ago










                                                                                                      • This answer is wrong. elit. Sed eget erat lectus. Morbi mi mi, fringilla sed (2nd line) is more than 50 characters. I'm using the newest Chrome.
                                                                                                        – mbomb007
                                                                                                        2 days ago












                                                                                                      • I was able to tweak my original suggestion to work in Chrome by putting the <p> inside the <tt>.
                                                                                                        – Neil
                                                                                                        2 days ago






                                                                                                      • 1




                                                                                                        next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
                                                                                                        – Neil
                                                                                                        2 days ago








                                                                                                      1




                                                                                                      1




                                                                                                      At least in my browser you can cut this down to (n,s)=>document.body.innerHTML+=`<p style=width:${n}ch><tt>${s}</tt></p>` for 74 bytes. If you're willing to dig out old versions of Firefox you can save another 8 bytes with (n,s)=>document.body.innerHTML+=`<pre wrap width=${n}>${s}</pre>` .
                                                                                                      – Neil
                                                                                                      2 days ago




                                                                                                      At least in my browser you can cut this down to (n,s)=>document.body.innerHTML+=`<p style=width:${n}ch><tt>${s}</tt></p>` for 74 bytes. If you're willing to dig out old versions of Firefox you can save another 8 bytes with (n,s)=>document.body.innerHTML+=`<pre wrap width=${n}>${s}</pre>` .
                                                                                                      – Neil
                                                                                                      2 days ago












                                                                                                      @Neil Nice use of ch units. Firefox 65 computes 50ch as 500px; Chromium 70 computes 50ch as 400px
                                                                                                      – guest271314
                                                                                                      2 days ago




                                                                                                      @Neil Nice use of ch units. Firefox 65 computes 50ch as 500px; Chromium 70 computes 50ch as 400px
                                                                                                      – guest271314
                                                                                                      2 days ago












                                                                                                      This answer is wrong. elit. Sed eget erat lectus. Morbi mi mi, fringilla sed (2nd line) is more than 50 characters. I'm using the newest Chrome.
                                                                                                      – mbomb007
                                                                                                      2 days ago






                                                                                                      This answer is wrong. elit. Sed eget erat lectus. Morbi mi mi, fringilla sed (2nd line) is more than 50 characters. I'm using the newest Chrome.
                                                                                                      – mbomb007
                                                                                                      2 days ago














                                                                                                      I was able to tweak my original suggestion to work in Chrome by putting the <p> inside the <tt>.
                                                                                                      – Neil
                                                                                                      2 days ago




                                                                                                      I was able to tweak my original suggestion to work in Chrome by putting the <p> inside the <tt>.
                                                                                                      – Neil
                                                                                                      2 days ago




                                                                                                      1




                                                                                                      1




                                                                                                      next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
                                                                                                      – Neil
                                                                                                      2 days ago




                                                                                                      next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
                                                                                                      – Neil
                                                                                                      2 days ago










                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote














                                                                                                      C# (Visual C# Interactive Compiler), 91 bytes





                                                                                                      s=>n=>s.Split(' ').Aggregate((a,w)=>a+(a.Length-a.LastIndexOf('n')+w.Length>n?'n':' ')+w)


                                                                                                      Try it online!






                                                                                                      share|improve this answer

























                                                                                                        up vote
                                                                                                        0
                                                                                                        down vote














                                                                                                        C# (Visual C# Interactive Compiler), 91 bytes





                                                                                                        s=>n=>s.Split(' ').Aggregate((a,w)=>a+(a.Length-a.LastIndexOf('n')+w.Length>n?'n':' ')+w)


                                                                                                        Try it online!






                                                                                                        share|improve this answer























                                                                                                          up vote
                                                                                                          0
                                                                                                          down vote










                                                                                                          up vote
                                                                                                          0
                                                                                                          down vote










                                                                                                          C# (Visual C# Interactive Compiler), 91 bytes





                                                                                                          s=>n=>s.Split(' ').Aggregate((a,w)=>a+(a.Length-a.LastIndexOf('n')+w.Length>n?'n':' ')+w)


                                                                                                          Try it online!






                                                                                                          share|improve this answer













                                                                                                          C# (Visual C# Interactive Compiler), 91 bytes





                                                                                                          s=>n=>s.Split(' ').Aggregate((a,w)=>a+(a.Length-a.LastIndexOf('n')+w.Length>n?'n':' ')+w)


                                                                                                          Try it online!







                                                                                                          share|improve this answer












                                                                                                          share|improve this answer



                                                                                                          share|improve this answer










                                                                                                          answered 2 days ago









                                                                                                          dana

                                                                                                          25114




                                                                                                          25114






















                                                                                                              up vote
                                                                                                              0
                                                                                                              down vote













                                                                                                              Mathematica, 16 bytes



                                                                                                              InsertLinebreaks


                                                                                                              Built-in function. Takes a string and an integer as input and returns a string as output.




                                                                                                              InsertLinebreaks["string", n]

                                                                                                               inserts newline characters to make no line longer than n characters.







                                                                                                              share|improve this answer



























                                                                                                                up vote
                                                                                                                0
                                                                                                                down vote













                                                                                                                Mathematica, 16 bytes



                                                                                                                InsertLinebreaks


                                                                                                                Built-in function. Takes a string and an integer as input and returns a string as output.




                                                                                                                InsertLinebreaks["string", n]

                                                                                                                 inserts newline characters to make no line longer than n characters.







                                                                                                                share|improve this answer

























                                                                                                                  up vote
                                                                                                                  0
                                                                                                                  down vote










                                                                                                                  up vote
                                                                                                                  0
                                                                                                                  down vote









                                                                                                                  Mathematica, 16 bytes



                                                                                                                  InsertLinebreaks


                                                                                                                  Built-in function. Takes a string and an integer as input and returns a string as output.




                                                                                                                  InsertLinebreaks["string", n]

                                                                                                                   inserts newline characters to make no line longer than n characters.







                                                                                                                  share|improve this answer














                                                                                                                  Mathematica, 16 bytes



                                                                                                                  InsertLinebreaks


                                                                                                                  Built-in function. Takes a string and an integer as input and returns a string as output.




                                                                                                                  InsertLinebreaks["string", n]

                                                                                                                   inserts newline characters to make no line longer than n characters.








                                                                                                                  share|improve this answer














                                                                                                                  share|improve this answer



                                                                                                                  share|improve this answer








                                                                                                                  edited yesterday

























                                                                                                                  answered yesterday









                                                                                                                  LegionMammal978

                                                                                                                  15k41752




                                                                                                                  15k41752






















                                                                                                                      up vote
                                                                                                                      0
                                                                                                                      down vote














                                                                                                                      Jelly, 12 bytes



                                                                                                                      ḲŒṖK€€ḣ€ƑƇṪY


                                                                                                                      Try it online!



                                                                                                                      Unfortunately, this is too slow to work for the provided test case in under a minute over TIO.






                                                                                                                      share|improve this answer

























                                                                                                                        up vote
                                                                                                                        0
                                                                                                                        down vote














                                                                                                                        Jelly, 12 bytes



                                                                                                                        ḲŒṖK€€ḣ€ƑƇṪY


                                                                                                                        Try it online!



                                                                                                                        Unfortunately, this is too slow to work for the provided test case in under a minute over TIO.






                                                                                                                        share|improve this answer























                                                                                                                          up vote
                                                                                                                          0
                                                                                                                          down vote










                                                                                                                          up vote
                                                                                                                          0
                                                                                                                          down vote










                                                                                                                          Jelly, 12 bytes



                                                                                                                          ḲŒṖK€€ḣ€ƑƇṪY


                                                                                                                          Try it online!



                                                                                                                          Unfortunately, this is too slow to work for the provided test case in under a minute over TIO.






                                                                                                                          share|improve this answer













                                                                                                                          Jelly, 12 bytes



                                                                                                                          ḲŒṖK€€ḣ€ƑƇṪY


                                                                                                                          Try it online!



                                                                                                                          Unfortunately, this is too slow to work for the provided test case in under a minute over TIO.







                                                                                                                          share|improve this answer












                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer










                                                                                                                          answered yesterday









                                                                                                                          Erik the Outgolfer

                                                                                                                          30.9k429102




                                                                                                                          30.9k429102






















                                                                                                                              up vote
                                                                                                                              0
                                                                                                                              down vote














                                                                                                                              C# (.NET Core), 162 bytes





                                                                                                                              stringt(string n,int a){var g="";for(int i=0;i++<Math.Floor((double)n.Length/a);)g+=$"^.{{{i*a-1}}}|";return Regex.Split(n,$@"(?n)(?<=({g.Trim('|')})S*)s");}}


                                                                                                                              This function uses a regex which matches the closest whitespace that is near the nth or multiple of nth character and splits the string based on it.



                                                                                                                              Try it online!



                                                                                                                              The TIO link is a full program, and the function has a static keyword so the function can be called from main.



                                                                                                                              Test Regex






                                                                                                                              share|improve this answer























                                                                                                                              • This doesn't give the right output for the test case - some lines are longer than 50 characters. You want "before" not "near", and also the splitting at one point must depend on where it was split earlier.
                                                                                                                                – Ørjan Johansen
                                                                                                                                20 hours ago

















                                                                                                                              up vote
                                                                                                                              0
                                                                                                                              down vote














                                                                                                                              C# (.NET Core), 162 bytes





                                                                                                                              stringt(string n,int a){var g="";for(int i=0;i++<Math.Floor((double)n.Length/a);)g+=$"^.{{{i*a-1}}}|";return Regex.Split(n,$@"(?n)(?<=({g.Trim('|')})S*)s");}}


                                                                                                                              This function uses a regex which matches the closest whitespace that is near the nth or multiple of nth character and splits the string based on it.



                                                                                                                              Try it online!



                                                                                                                              The TIO link is a full program, and the function has a static keyword so the function can be called from main.



                                                                                                                              Test Regex






                                                                                                                              share|improve this answer























                                                                                                                              • This doesn't give the right output for the test case - some lines are longer than 50 characters. You want "before" not "near", and also the splitting at one point must depend on where it was split earlier.
                                                                                                                                – Ørjan Johansen
                                                                                                                                20 hours ago















                                                                                                                              up vote
                                                                                                                              0
                                                                                                                              down vote










                                                                                                                              up vote
                                                                                                                              0
                                                                                                                              down vote










                                                                                                                              C# (.NET Core), 162 bytes





                                                                                                                              stringt(string n,int a){var g="";for(int i=0;i++<Math.Floor((double)n.Length/a);)g+=$"^.{{{i*a-1}}}|";return Regex.Split(n,$@"(?n)(?<=({g.Trim('|')})S*)s");}}


                                                                                                                              This function uses a regex which matches the closest whitespace that is near the nth or multiple of nth character and splits the string based on it.



                                                                                                                              Try it online!



                                                                                                                              The TIO link is a full program, and the function has a static keyword so the function can be called from main.



                                                                                                                              Test Regex






                                                                                                                              share|improve this answer















                                                                                                                              C# (.NET Core), 162 bytes





                                                                                                                              stringt(string n,int a){var g="";for(int i=0;i++<Math.Floor((double)n.Length/a);)g+=$"^.{{{i*a-1}}}|";return Regex.Split(n,$@"(?n)(?<=({g.Trim('|')})S*)s");}}


                                                                                                                              This function uses a regex which matches the closest whitespace that is near the nth or multiple of nth character and splits the string based on it.



                                                                                                                              Try it online!



                                                                                                                              The TIO link is a full program, and the function has a static keyword so the function can be called from main.



                                                                                                                              Test Regex







                                                                                                                              share|improve this answer














                                                                                                                              share|improve this answer



                                                                                                                              share|improve this answer








                                                                                                                              edited yesterday

























                                                                                                                              answered yesterday









                                                                                                                              Embodiment of Ignorance

                                                                                                                              1507




                                                                                                                              1507












                                                                                                                              • This doesn't give the right output for the test case - some lines are longer than 50 characters. You want "before" not "near", and also the splitting at one point must depend on where it was split earlier.
                                                                                                                                – Ørjan Johansen
                                                                                                                                20 hours ago




















                                                                                                                              • This doesn't give the right output for the test case - some lines are longer than 50 characters. You want "before" not "near", and also the splitting at one point must depend on where it was split earlier.
                                                                                                                                – Ørjan Johansen
                                                                                                                                20 hours ago


















                                                                                                                              This doesn't give the right output for the test case - some lines are longer than 50 characters. You want "before" not "near", and also the splitting at one point must depend on where it was split earlier.
                                                                                                                              – Ørjan Johansen
                                                                                                                              20 hours ago






                                                                                                                              This doesn't give the right output for the test case - some lines are longer than 50 characters. You want "before" not "near", and also the splitting at one point must depend on where it was split earlier.
                                                                                                                              – Ørjan Johansen
                                                                                                                              20 hours ago












                                                                                                                              up vote
                                                                                                                              0
                                                                                                                              down vote














                                                                                                                              05AB1E, 18 bytes



                                                                                                                              õs#vDy«g²›i,}yðJ}?


                                                                                                                              Try it online.



                                                                                                                              Explanation:





                                                                                                                              õ                   # Push an empty string "" to the stack
                                                                                                                              s # Swap to take the (implicit) string input
                                                                                                                              # # Split it by spaces
                                                                                                                              v } # For-each `y` over the words:
                                                                                                                              D # Duplicate the top of the stack
                                                                                                                              # (which is the empty string in the very first iteration)
                                                                                                                              y« # Append the current word `y`
                                                                                                                              g # Get its length
                                                                                                                              ²›i } # If its lengthy is larger than the second input:
                                                                                                                              , # Pop and output the current duplicated value with trailing newline
                                                                                                                              yð # Push the word `y` and a space " "
                                                                                                                              J # Join the entire stack together
                                                                                                                              ? # After the loop, output the last part as well (without newline)





                                                                                                                              share|improve this answer

























                                                                                                                                up vote
                                                                                                                                0
                                                                                                                                down vote














                                                                                                                                05AB1E, 18 bytes



                                                                                                                                õs#vDy«g²›i,}yðJ}?


                                                                                                                                Try it online.



                                                                                                                                Explanation:





                                                                                                                                õ                   # Push an empty string "" to the stack
                                                                                                                                s # Swap to take the (implicit) string input
                                                                                                                                # # Split it by spaces
                                                                                                                                v } # For-each `y` over the words:
                                                                                                                                D # Duplicate the top of the stack
                                                                                                                                # (which is the empty string in the very first iteration)
                                                                                                                                y« # Append the current word `y`
                                                                                                                                g # Get its length
                                                                                                                                ²›i } # If its lengthy is larger than the second input:
                                                                                                                                , # Pop and output the current duplicated value with trailing newline
                                                                                                                                yð # Push the word `y` and a space " "
                                                                                                                                J # Join the entire stack together
                                                                                                                                ? # After the loop, output the last part as well (without newline)





                                                                                                                                share|improve this answer























                                                                                                                                  up vote
                                                                                                                                  0
                                                                                                                                  down vote










                                                                                                                                  up vote
                                                                                                                                  0
                                                                                                                                  down vote










                                                                                                                                  05AB1E, 18 bytes



                                                                                                                                  õs#vDy«g²›i,}yðJ}?


                                                                                                                                  Try it online.



                                                                                                                                  Explanation:





                                                                                                                                  õ                   # Push an empty string "" to the stack
                                                                                                                                  s # Swap to take the (implicit) string input
                                                                                                                                  # # Split it by spaces
                                                                                                                                  v } # For-each `y` over the words:
                                                                                                                                  D # Duplicate the top of the stack
                                                                                                                                  # (which is the empty string in the very first iteration)
                                                                                                                                  y« # Append the current word `y`
                                                                                                                                  g # Get its length
                                                                                                                                  ²›i } # If its lengthy is larger than the second input:
                                                                                                                                  , # Pop and output the current duplicated value with trailing newline
                                                                                                                                  yð # Push the word `y` and a space " "
                                                                                                                                  J # Join the entire stack together
                                                                                                                                  ? # After the loop, output the last part as well (without newline)





                                                                                                                                  share|improve this answer













                                                                                                                                  05AB1E, 18 bytes



                                                                                                                                  õs#vDy«g²›i,}yðJ}?


                                                                                                                                  Try it online.



                                                                                                                                  Explanation:





                                                                                                                                  õ                   # Push an empty string "" to the stack
                                                                                                                                  s # Swap to take the (implicit) string input
                                                                                                                                  # # Split it by spaces
                                                                                                                                  v } # For-each `y` over the words:
                                                                                                                                  D # Duplicate the top of the stack
                                                                                                                                  # (which is the empty string in the very first iteration)
                                                                                                                                  y« # Append the current word `y`
                                                                                                                                  g # Get its length
                                                                                                                                  ²›i } # If its lengthy is larger than the second input:
                                                                                                                                  , # Pop and output the current duplicated value with trailing newline
                                                                                                                                  yð # Push the word `y` and a space " "
                                                                                                                                  J # Join the entire stack together
                                                                                                                                  ? # After the loop, output the last part as well (without newline)






                                                                                                                                  share|improve this answer












                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer










                                                                                                                                  answered 20 hours ago









                                                                                                                                  Kevin Cruijssen

                                                                                                                                  34.6k554183




                                                                                                                                  34.6k554183






















                                                                                                                                      up vote
                                                                                                                                      0
                                                                                                                                      down vote













                                                                                                                                      Java 8, 135 bytes





                                                                                                                                      n->s->{String r="",S=s.split(" "),t=r;for(int i=0;i<S.length;)if((t+S[i]).length()>n){r+=t+"n";t="";}else t+=S[i++]+" ";return r+t;}


                                                                                                                                      Try it online.



                                                                                                                                      Explanation:



                                                                                                                                      n->s->{                      // Method with integer & String parameters and String return
                                                                                                                                      String r="", // Result-String, starting empty
                                                                                                                                      S=s.split(" "), // Input-String split by spaces
                                                                                                                                      t=r; // Temp-String, starting empty as well
                                                                                                                                      for(int i=0;i<S.length;) // Loop `i` in the range [0, amount_of_words):
                                                                                                                                      if((t+S[i]).length()>n){ // If `t` and the word are larger than the integer input:
                                                                                                                                      r+=t+"n"; // Add `t` and a newline to the result
                                                                                                                                      t="";} // And reset `t` to an empty String
                                                                                                                                      else // Else:
                                                                                                                                      t+=S[i++]+" "; // Append the word and a space to `t`
                                                                                                                                      // (and then increase `i` by 1 with `i++` for the next word
                                                                                                                                      // of the next iteration)
                                                                                                                                      return r+t;} // Return the result-String appended with `t` as result





                                                                                                                                      share|improve this answer

























                                                                                                                                        up vote
                                                                                                                                        0
                                                                                                                                        down vote













                                                                                                                                        Java 8, 135 bytes





                                                                                                                                        n->s->{String r="",S=s.split(" "),t=r;for(int i=0;i<S.length;)if((t+S[i]).length()>n){r+=t+"n";t="";}else t+=S[i++]+" ";return r+t;}


                                                                                                                                        Try it online.



                                                                                                                                        Explanation:



                                                                                                                                        n->s->{                      // Method with integer & String parameters and String return
                                                                                                                                        String r="", // Result-String, starting empty
                                                                                                                                        S=s.split(" "), // Input-String split by spaces
                                                                                                                                        t=r; // Temp-String, starting empty as well
                                                                                                                                        for(int i=0;i<S.length;) // Loop `i` in the range [0, amount_of_words):
                                                                                                                                        if((t+S[i]).length()>n){ // If `t` and the word are larger than the integer input:
                                                                                                                                        r+=t+"n"; // Add `t` and a newline to the result
                                                                                                                                        t="";} // And reset `t` to an empty String
                                                                                                                                        else // Else:
                                                                                                                                        t+=S[i++]+" "; // Append the word and a space to `t`
                                                                                                                                        // (and then increase `i` by 1 with `i++` for the next word
                                                                                                                                        // of the next iteration)
                                                                                                                                        return r+t;} // Return the result-String appended with `t` as result





                                                                                                                                        share|improve this answer























                                                                                                                                          up vote
                                                                                                                                          0
                                                                                                                                          down vote










                                                                                                                                          up vote
                                                                                                                                          0
                                                                                                                                          down vote









                                                                                                                                          Java 8, 135 bytes





                                                                                                                                          n->s->{String r="",S=s.split(" "),t=r;for(int i=0;i<S.length;)if((t+S[i]).length()>n){r+=t+"n";t="";}else t+=S[i++]+" ";return r+t;}


                                                                                                                                          Try it online.



                                                                                                                                          Explanation:



                                                                                                                                          n->s->{                      // Method with integer & String parameters and String return
                                                                                                                                          String r="", // Result-String, starting empty
                                                                                                                                          S=s.split(" "), // Input-String split by spaces
                                                                                                                                          t=r; // Temp-String, starting empty as well
                                                                                                                                          for(int i=0;i<S.length;) // Loop `i` in the range [0, amount_of_words):
                                                                                                                                          if((t+S[i]).length()>n){ // If `t` and the word are larger than the integer input:
                                                                                                                                          r+=t+"n"; // Add `t` and a newline to the result
                                                                                                                                          t="";} // And reset `t` to an empty String
                                                                                                                                          else // Else:
                                                                                                                                          t+=S[i++]+" "; // Append the word and a space to `t`
                                                                                                                                          // (and then increase `i` by 1 with `i++` for the next word
                                                                                                                                          // of the next iteration)
                                                                                                                                          return r+t;} // Return the result-String appended with `t` as result





                                                                                                                                          share|improve this answer












                                                                                                                                          Java 8, 135 bytes





                                                                                                                                          n->s->{String r="",S=s.split(" "),t=r;for(int i=0;i<S.length;)if((t+S[i]).length()>n){r+=t+"n";t="";}else t+=S[i++]+" ";return r+t;}


                                                                                                                                          Try it online.



                                                                                                                                          Explanation:



                                                                                                                                          n->s->{                      // Method with integer & String parameters and String return
                                                                                                                                          String r="", // Result-String, starting empty
                                                                                                                                          S=s.split(" "), // Input-String split by spaces
                                                                                                                                          t=r; // Temp-String, starting empty as well
                                                                                                                                          for(int i=0;i<S.length;) // Loop `i` in the range [0, amount_of_words):
                                                                                                                                          if((t+S[i]).length()>n){ // If `t` and the word are larger than the integer input:
                                                                                                                                          r+=t+"n"; // Add `t` and a newline to the result
                                                                                                                                          t="";} // And reset `t` to an empty String
                                                                                                                                          else // Else:
                                                                                                                                          t+=S[i++]+" "; // Append the word and a space to `t`
                                                                                                                                          // (and then increase `i` by 1 with `i++` for the next word
                                                                                                                                          // of the next iteration)
                                                                                                                                          return r+t;} // Return the result-String appended with `t` as result






                                                                                                                                          share|improve this answer












                                                                                                                                          share|improve this answer



                                                                                                                                          share|improve this answer










                                                                                                                                          answered 15 hours ago









                                                                                                                                          Kevin Cruijssen

                                                                                                                                          34.6k554183




                                                                                                                                          34.6k554183






























                                                                                                                                              draft saved

                                                                                                                                              draft discarded




















































                                                                                                                                              If this is an answer to a challenge…




                                                                                                                                              • …Be sure to follow the challenge specification. However, please refrain from exploiting obvious loopholes. Answers abusing any of the standard loopholes are considered invalid. If you think a specification is unclear or underspecified, comment on the question instead.


                                                                                                                                              • …Try to optimize your score. For instance, answers to code-golf challenges should attempt to be as short as possible. You can always include a readable version of the code in addition to the competitive one.
                                                                                                                                                Explanations of your answer make it more interesting to read and are very much encouraged.


                                                                                                                                              • …Include a short header which indicates the language(s) of your code and its score, as defined by the challenge.



                                                                                                                                              More generally…




                                                                                                                                              • …Please make sure to answer the question and provide sufficient detail.


                                                                                                                                              • …Avoid asking for help, clarification or responding to other answers (use comments instead).






                                                                                                                                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                                                                                                              Please pay close attention to the following guidance:


                                                                                                                                              • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                              But avoid



                                                                                                                                              • Asking for help, clarification, or responding to other answers.

                                                                                                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                              To learn more, see our tips on writing great answers.




                                                                                                                                              draft saved


                                                                                                                                              draft discarded














                                                                                                                                              StackExchange.ready(
                                                                                                                                              function () {
                                                                                                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f176870%2fmake-a-simple-word-wrapper%23new-answer', 'question_page');
                                                                                                                                              }
                                                                                                                                              );

                                                                                                                                              Post as a guest















                                                                                                                                              Required, but never shown





















































                                                                                                                                              Required, but never shown














                                                                                                                                              Required, but never shown












                                                                                                                                              Required, but never shown







                                                                                                                                              Required, but never shown

































                                                                                                                                              Required, but never shown














                                                                                                                                              Required, but never shown












                                                                                                                                              Required, but never shown







                                                                                                                                              Required, but never shown







                                                                                                                                              Popular posts from this blog

                                                                                                                                              Bressuire

                                                                                                                                              Cabo Verde

                                                                                                                                              Gyllenstierna