[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](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortes solution in bytes wins.
[Here](https://tio.run/##jVPbitwwDH3PV4h5SiCEQulLof2Ctiz0sS2LxlYSLbbs9WW3/fqpnGQ6vbDQEEKsy9E5Rzj@KGuQ15eLpRmeE8b7Qt9L3z4jOJKlrMPbDvR5DslmeActNeXouPQnOA1bzrFQy335th1NTYmk3LfwHt3Cc0gbCrDsaDvw3x0Txkhi@1Yy/KrgudFpI6eHwNL/3jEM8P4ge4P8BzaG2A9/pDfa13EvIL@I14Q1ioe4/8baPolKTbI3dV2z7vQhJPLAMVcPNjj1KnMB9KSLMEEymdKaAC1HzoZlAdIlTPCZLNBCBShhURtMqXmCjyGdGXx7R5iTlrNzCFmLc9X2qOBVI96EFCmNUBLnwo@VQFE8Vj1eUSSIUvA@2ADC53WCO3Lqd6Hc6lc8c0HRrq36BpRJNjag5ISOH4@OckWLMKu4DGhAZamkJiIXzLsiJcFoqtP4lcxdQlJINUWRPWBdKk3wqak4ZEPGyCSj5kxRB3U8xBXV7YRAVUWyGLa1YRiwjH4f5nipCoLJaA06JY8eHqvOfmoeX0OjtugYD0@YuKlRw6cTdKL7e/Oq66LarLfiqxzbv92nPIIMw3C5/AQ "Python 3 – Try It Online") is an example program in Python that would work.
  
[Answer]
# [Python 2](https://docs.python.org/2/), 26 bytes
```
from textwrap import*
fill
```
[Try it online!](https://tio.run/##VZDNSgRBDITv@xR1dGUYVPDoG6gIHkUk25OZDfSf6fSqT79mdBcR@pBOV1fqS/2yfck3x@OsJcH40z6UKiTVona5mSXG44w7rMWmqmTDfKH08Sa5drvYDnj5dzsVry/Xr9vjfVFOkNp6wlRiUTQxUGIbEEpuHIytK2iSKi1IXsBRbMQzT@CFDaxkiK7rbcRD0Z0grWfA7FkWD0VoLm7dv1c3795JoWhlHWAqzeS9M9wlUffr2SWX7BFSKlNBlt1@xBPHyNm4rfo97cTIYdOP@s@ocf5JAw@X@VQkitw6TYTZ4RoowLEcaYVoRu2XyEMIhR69fw7zpMRu6Utx5wTqS@cRjyvFCRuNqnAe/C2Yb9DHo@5J2ZTA3SElB5n66hEwCaXfYVGW7iakwTUUPTwlvHeffVh3fG4N/sXHJBxIZaXxhY@bze3VNw "Python 2 – Try It Online\"oXcyiLN1FSIPPUPTwlHDq7v217fjWGvyL2yR8kcpG4wsf73YvT38 \"Python 2 – 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!](https://tio.run/##RZDNTsMwEITvfYoRlwBNI4TEBegbAELiCbbONl3Jf3jtKlx49bKBVkg5OOvxzHybv@ohxfvTSfu4lZhbvb5ZzduuW@1TgUAidNDsxeaPbhufPcfreS03Tzyz63KRWDF3t@5p3s63m@@NW8u6Q7c635xOVy@pcIBkbQFj8marUkGBaw@XorKrXFsBjZJFncQJbHkDPngET1zBhSq86ZoOeE1lJwjL12NvKZN4T1ATa7Pn2cybTYJLJXPpUYtolc/GMJdAzX4vLjFFqxBCGhOi7A4D3tkbYWVd9AfaSSXDCL/qfyPl@NsGVi7y@RDIszYaCXuDU5CDYRnSAqGV9I/ISgi55m1@KfNeiM3SlmLOAdSmxgPeFoozNpSycOztzlXboMUjH6hwLQRuBinRydgWD4dRKPyFeZmamVBxpiFv5Sngs1n2cdnxZdTbE4sJOFKRhcYWPlz1eLj7AQ "Python 2 – Try It Online")
Outputs trailing spaces.
[Answer]
# [PHP](https://php.net/), 8 bytes
Admittedly not the most original solution, but PHP has a native function that matches your requirements perfectly!
## [`wordwrap`](http://php.net/manual/en/function.wordwrap.php):
> 
> `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!](https://tio.run/##RZFLbsMwDET3OcUg6KIFDKObrtKiF2iLAD0BIzM2Af1CScnxXSofFPBCpobDeVRe8rq@f@Ylb55KVXxg@5WUAySXFjAlnxRFKihwHeBSLOwq16agSbIUJ3EGe6kjfnkCz1zBShXedK2M@E56EIT@DTiqycV7QjFxadaezbxZJbikmXVAVSlVTo1hLoGa/T5cYooWIYQ0JUQ5LCP27D3HyqXrFzpIpWhdV/W/UeF4TQMLF/l@COS5NJoIR4MrIAfDMqQOUSqVG5GFEHLNW/0RZq/EZmlLMecAanPjET@d4o6NQlk4Dnbnqm3QxiMvpFyVwM0gJTqZWvdwmITCbZiXuZkJqTMNeQtPAadms899x4/SYC02JuBMKp3GFj5udxt2S8Il6XRRys/9QQe8vb7s1vUP "PHP – Try It Online")
[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!](https://tio.run/##RZBNbhsxDIX3PQWRRTyDmQyyySaAnAu0gYEuiwKmNfSYgf5MSvbxXU4So4AWEvX4@D5@4AXVC5f6lPJMt6O7qdsmt9VJS@C6h/0UsXRXtxXXNSdvMmxgM1xfr/2f9Pety4OTYf9jP1771zZmJ26z6R8f8yA3n5PmQFPIS3fsHn5moQhctEWYc8gCyhUwUh1hlZKvVJsAzlxYPacFyBJM8JtmoIUqkGCFYLqmE/zKcmCI6xnhKCbnEBDUxNqsvZh5s0r0WQrJCFVYK58bgblEbPa8u6ScLEKMec6Q@HCaYEchUKqkq/6EB66YrOtT/d9IKX2mAQuX6PsSMZA2nBGOBqeAHgzLkFYIrahfRBaC0bdg9XuYnSCZpS3FnCNgWxpN8L5SfGODYmFKo/35ahu08VBOKFQFgZpBcvI8t9XDw8wYv4YFXpqZoHjTYLDwGOHcbPZl3fG9NFqLjYlwQeGVxhY@PfTdy3Pf3/4B "JavaScript (Node.js) – 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":
$$\small\begin{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&&&&&&&&&&&&\\ \hline\end{array}
$$
Adding "IPSUM":
$$\small\begin{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&&&&&&\\ \hline\end{array}
$$
Adding "DOLOR":
$$\small\begin{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\\ \hline\end{array}
$$
$$\small\begin{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&&&&&&&&&&&&\\ \hline\end{array}
$$
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~46~~ 29 bytes
```
{;*.comb(/.**{1..$_}[\s|$]/)}
```
[Try it online!](https://tio.run/##RZDNSkMxEIVf5VBE2nKJutCN2CdQKbhUkWnutB3IzzWTFIr67HVuaxGySCZnzpxvBi7h7hD3uFzjAYev@7nzOa6mV24@/7px7uLj5/VNvy/er2Y/h/X09no2nTzmwhEyaIvoc8gFKhUUuXbwOSn7yrUVUC@DqJe0AQepDi/cgzdcwYUqgumaOjzlshLE8XRYF5NLCAQ1sTZrH8y8WSX6XAYuHWoRrfLZGOYSqdnz7JJysggx5j4jyWrrsOQQOFXWUb@llVRK1nVU/xspp2MaWLjEf5dIgbVRT1gbnII8DMuQRgitpCciCyHkW7D6OcyyEJulLcWcI6htGjs8jxR/2FAahFNnf77aBm08hi0VroXAzSAleenb6OHRC8XTsCCbZiZUvGkoWHiK@Gw2ezfu@FzqrMXGROyoyEhjC3eT2WLhlPaHXw "Perl 6 – 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
```
[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](https://tio.run/##RZBLTsRADET3LDlBHSCK2LBB4gaARuIAyNPxZCz1J9O2w/GDMx8h9aLbXS7X87ptb8qw3/dnepovP9v20ToXyKJeMLXcOlQMVNgGpFaVk7F5B02yiCapMziLjfjmCTyzgTsZcuhcR3y2fhSU/Qw49ZBLzgQNsXq0L2HuUSmp9YX7AOuiJhdnhEshj@fDpbYaEUppU0OV43nEgXPmaqy7/kxHMarRdVX/GynXaxpEuMr3S6HM6jQRTgGnoITACqQdQo30RhQhhJLnqD/CHDpxWMZSwrmAfHYe8bVT3LGhtAjXIf6SxQZjPJYzdbZOYA9IqUkm3z0SJqFyG5Zl9jChnkJDOcJTwcVj9rrv@FEaoiXGFKzUZaeJhY/b68sf "V – Try It Online"), 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!](https://tio.run/##RZBLbsMwDET3OcUcwDG66aZos@m2LQL0AAUjsQ4BfRxSSo7v0vmggCFY1HA4j@dleTFGu7y9vm9158dlt4lxOv0sy/PT5qMqZ8hsPSPWVBUmDZS5DQi1GIfGrSsoyiwWpEzgJG3EN0fwxA2s1JBc123EZ9WDIK/fgF91uaREMBdb9/bZzbtXcqg6sw5oKtbk1Bnukqn79eFSavEIOddYUeRwHLHnlLg0tlV/pIM0Kt51Vf8bGZdrGni4wvefTImtUyT8OpyBAhzLkVYIa2Q3Ig8hFHry@iPMXond0pfizhnUp84jvlaKOzaMZuEy@FtovkEfj/lIyk0J3B1SSpDYV4@AKJRvw5JM3U1Ig2soeXjKOHWffV53/CgN3uJjMs6kstL4wsdle/4D "V – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~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!](https://tio.run/##RZFNTsNADIX3PcUTKypCBAt2cANAlTiBO3FaS/OT2jPl@MHTHyFlMfE8P7/Po@v8/rzOLYcqJT/akLdW9Vdp6een1@1q@MDDZ1FOkMVawlRiUZhUUOI6IJRsHCrXpqBJFrEg@QCOUkf88AQ@cAUrVUTXNRvxVXQvSP0bMKvLJUaCudiaty9u3rySQtGFdUBVsSqnxnCXRM1/7y65ZI@QUpkKsuyPI3YcI@fK1vVH2kul7F0X9b@Rcb6kgYfLfDskimyNJsLscAYKcCxH6hBWya5EHkIotOj1e5idErulL8WdE6gdGo/47hQ3bBgtwnnwu1B9gz4ey5GUqxK4OaTkIFPrHgGTULoOi3JobkIaXEPRw1PCqfnsc9/xvTR4i49JOJNKp/GFjw/YZH@/t5fNZr487voH "R – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 70 bytes
```
s!n|length s<=n=[s]|(t,_:d)<-splitAt(until((<'!').(s!!))pred n)s=t:d!n
```
[Answer]
# [Python 2](https://docs.python.org/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!](https://tio.run/##RZDNbtwwDITvfYrBXvLnGG2BXna7b9AEAXpc5MCVGZuARCmilJ@n39JJFgUM2KJHM/OxvLcl68/TyQbdi5beLq@@vS4SGbaVve74jcNGbvcXuPh9aTf@utargzzuNte6K1W0wQ5bP9veDnLzY/t4Om3@5MoJUqwnTDnmCpMGStwGhKzGoXHrFTRJEQuiMzhKG/GXJ/DMDVypIbqu24i7XI@CtD4DnjxzlhgJ5mLrfr24efdJCrkWrgNaFWvy3Bnukqj78eyiWb1CSnnKUDkuIx44RtbGtuoXOkojh0of6v9GxvrRBl5O@esjUWTrNBGeHM5AAY7lSCuENbJPIi8hFHr0@bnMQyV2S1@KOydQnzuPuF8pvrBhVIR18H@h@QY9HmWhyq0SuDukaJCprx4Bk1D6DIsydzehGlxD0ctTwnP37Jd1x@fR4Fc8JuGFqqw0vvBxM@DX938 "Python 2 – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 46 44 bytes
Basically a pure regex solution in Java, almost certainly the shortest I've written.
Cheers to Kevin for helping to cut down the bytes in the regex even further!
```
n->s->s.replaceAll(".{1,"+n+"}( |$)","$0\n")
```
[Try it online!](https://tio.run/##fZFJaxtBEIXv@hWPwQcNHjfOIScnglwMgTgYdExyKPWUpJJ7cy8C4@i3KzVayM3QML1Uvfremx3t6W43vhyto1LwRBLeZ0CpVMVip6@mVXFm3YKtEoN5vGy@fA@VN5yHD4uWNUvYDDh/Fwus8fUY7hZFl8mcHFn@5ty8M@@fhu423HaHOf7e9N3Q3dz/Dl1/fJgpTmorpzgXqn2UEV5J52fZX39A/UQNLN9KZW9iqybpU3VhvjaUknubf77vL7vuR8zsIak0jzG6mFGkgjzXATaGwrZybRk0SpJidQTYSTVY8gg1XcGZKpzWtWLwFPNK4Kc1YD0RiXOEosWlaXtS8aY33sacpsSUulR5bQxV8dT0eFUJMSiC93GMCLLaGjyzc6xZl6l@SyupFLTrVP1fqHA40UDhAl82nhyXRiNhreYKyEJtqaXJhIZZzo4UQsg2p/dXmOdMrJIaiip7UNs0Nvg5ubjYRqEkHAZ9s1UT1PFIW8pcM4GbmpRgZWyThsUo5M/DnGyailC2WkNO4cnjtens/ZTx9WrQFh3jsacsOo2wgj3Fbrq@f9CffZgdjv8A "Java (JDK) – Try It Online")
Using a curried lamdba, it creates a regex to greedily match up to `n` characters followed by either a space or end of string. It then replaces those characters with themselves followed by a newline.
[Answer]
# Mathematica, 16 bytes
```
InsertLinebreaks
```
Built-in function. Takes a string and an integer as input and returns a string as output.
> 
> `[InsertLinebreaks](https://reference.wolfram.com/language/ref/InsertLinebreaks.html)["*string*", *n*]`  
> 
>   inserts newline characters to make no line longer than *n* characters.
> 
> 
> 
[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
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 68 bytes
```
i;b(s,n,l)char*s,*l;{for(i=n;*++s;i--||(i=l-s+n,*l=10))l=*s-32?l:s;}
```
[Try it online!](https://tio.run/##RVLLTiMxELzzFS1OmWRmBLvay46i/QFASBxXHDqezqQlPwa3zQX49mwZiFbyod2urq4q2Q2Lc@ezToeN9bH3nTtx3lq/9dPbMeWN7uO03e1s0mF4f8fVD7aLeN7f3nSd329t@Pnjj/9t08c5sMZN93ZFjYPs7/P@@i5lCaSr1UBz8gltLcRBSk8uRRNXpNRMPOuq5jQuJF7LSE8ykyxSSDIX8sBVG@k@5YNSaKenYwZcvWcygK1ifAV5RSe4lFfJPZWsVvSlCoElcMX1whJThIQQ0pwo6uE00qN4L7GINfyJD1o4YuoT/Z/IJH6qIYiL8l0E9mKVZ6YjzBmxI9iCpWbCCtuXI4hQdtWjfxHzmFlAiVDAHIjrUmWkh@bi2zYZryqxx5srSBDraUXCUjKTVJjU6HSujcPRrBy@lnldKkg4O2DYQzwHeqnY/doyvrR6jGBNoFfO2twg8PF6uqL2I37ddKjWWmxjqD7O/wA "C (gcc) – Try It Online")
Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat), save 2 bytes by moving global `char*l` to parameter.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Infix function; left argument is `n`, right argument is `n`.
```
⎕CY'dfns'⋄wrap
```
[Try it online!](https://tio.run/##RZBLahxBEESvErvZtAaD8Qm0kcAf4fHGy5yq7J6E@rTqI@G1hBYyFvbC5/AdfJS@yDha0mBoiq6syMh4KXM4898k5Ol4XJ5@n3/d@DHVzfL9/rbIfByXh5/Ljye@XH5aHu/@/nm7PPzibff5nOeXi8vd8d0bjNi8z0UjbK49wueQC6o1SNQ2wOVU1TVtvUC8zVadpQkarG2xUw@dtEGLNATqet3iQy57Q1y/AWOh3EIQVIprZ/tM885KdLnMWga0YrXZdVfQJUrn9eSScmKEGLPPSLY/bHGlIWhqWlf9QfbWJLHrWf3fqGp6TgOGS/r6EyVo7eIFI@EqxIFYRFohapP6QsQQJq4H1k9hroooLbkUOkdIn7pu8XGleMVGldk0DXxzjRvkeMwHKdqKQDshLTnzffVw8CbxZViwqdNEiqNGAsNLxHXn7Jt1x6fSwBaOibiRYisNF775Bw "APL (Dyalog Unicode) – Try It Online")
`⎕CY` **c**op**y** in [the dfns library](http://dfns.dyalog.com/n_contents.htm)
`⋄` then
`wrap`[[c]](http://dfns.dyalog.com/c_wrap.htm "Code") use the wrap[[n]](http://dfns.dyalog.com/n_wrap.htm "Notes") function
[c] code of that function  
[n] notes for that function
---
### Golfed version of `wrap`, 59 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
```
{⍺≥≢⍵:⍵⋄(t↑⍵),2↓⎕TC,⍺∇⍵↓⍨t+b⊃⍨t←⊃⌽⍺,g/⍨⍺≥g←⍸(⍺+1)↑b←' '=⍵}
```
[Try it online!](https://tio.run/##RVDNahRBEH6Vum1CxjUqXgRPuSRgNLi@QE1P7WxD/0z6JyDiKbKa6C5KyAsIgrecAiJ48VH6RTZf72YJzEB11VffT/FgHnXv2fh@VZbXR2/K/Pv@6kNZ/C0Xv8rFz7K4fYG/fP20k8r8B8rd5mmZXwH77qCpsC@f6xydxe@015bL81qApVbf/gHR9I/R2jD2dbD4s4PX3pNdELZojGj0EhwfV9P1dLnxcXn@/@ZZlVxeT94eVL3Do8nq@T5NafTKB7Gkh5gtdd74QFEnYiupIeVdFJUk5UDc6UFHpV1PYnQa00Q6kl4SSeBEBrgcx3TsQ6vJ1q@haQBcG8MUAY4Z6wPIMzpW@TBIaCgFHZM@zUJgsZzx3LI472DBWt95crqdjelEjBGXJFb8jFud2GFrjX4giuLWbgjmnNwXlo3EzB3TFOEisSLEQqQaIiaOm0QwoVllg/7WzElgASWOAmZLnPssY3pdU9zHpsiDFtdgphIuCHkaZhwkBSbJCKmd0l2uHIo6zXYjZnSfQcJBAcMG5tnSaYb2Wb3xttVgBTKWzjjomgYHH90B "APL (Dyalog Unicode) – Try It Online")
`{`…`}` dfn; `⍺` is left argument (width), `⍵` is right argument (string)
 `≢⍵` tally (number of characters) of string
 `⍺≥`…`:` if width is greater than or equal to that, then:
  `⍵` return the string
 `⋄` otherwise:
  `' '=⍵` Boolean mask where blanks are equal to the string
  `b←` store in `b` (for **b**lanks)
  `(`…`)↑` take the following number of elements from that:
   `⍺+1` one more than the width
  `⍸` **i**ndices where true
  `g←` store in `g` (for **g**aps)
  `⍺≥` Boolean mask where the width is greater than or equal to that
  `g/⍨` filter the gap indices by that
  `⍺,` append that to the width
  `⊃⌽` pick the last element of that (lit. pick the first of the reversed)
  `t←` store in `t` (for **t**ake)
  `b⊃⍨` use that to pick an element from the mask of **b**lanks
  `t+` add that to `t`
  `⍵↓⍨` drop that many characters from the string
  `⍺∇` recurse on that with the same left left argument
  `⎕TC,` append that to the list of **t**erminal **c**ontrol characters (8:HT, 10:NL, 13:CR)
  `2↓` drop the first two character from that (leaving just a leading 13:CR)
  `(`…`),` append that to the following:
   `t↑⍵` the first `t` characters of the string
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 bytes
```
¸rÈ+Yi[X·ÌY]¸Ê>V?R:S
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=uHJAW1hZXXEoWLfMK1MrWSDKPlY/UjpT&input=IkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0LCBjb25zZWN0ZXR1ciBhZGlwaXNjaW5nIGVsaXQuIFNlZCBlZ2V0IGVyYXQgbGVjdHVzLiBNb3JiaSBtaSBtaSwgZnJpbmdpbGxhIHNlZCBzdXNjaXBpdCB1bGxhbWNvcnBlciwgdHJpc3RpcXVlIGF0IG1hdXJpcy4gTW9yYmkgbm9uIGNvbW1vZG8gbmliaC4gUGVsbGVudGVzcXVlIGhhYml0YW50IG1vcmJpIHRyaXN0aXF1ZSBzZW5lY3R1cyBldCBuZXR1cyBldCBtYWxlc3VhZGEgZmFtZXMgYWMgdHVycGlzIGVnZXN0YXMuIFNlZCBhdCBpYWN1bGlzIG1hdXJpcy4gUHJhZXNlbnQgYSBzZW0gYXVndWUuIE51bGxhIGxlY3R1cyBzYXBpZW4sIGF1Y3RvciBuZWMgcGhhcmV0cmEgZXUsIHRpbmNpZHVudCBhYyBkaWFtLiBTZWQgbGlndWxhIGFyY3UsIGFsaXF1YW0gcXVpcyB2ZWxpdCBhbGlxdWFtLCBkaWN0dW0gdmFyaXVzIGVyYXQuIgo1MAo=)
Thanks to Bubbler and Shaggy for their help
Explanation:
```
¸                       #Split into words
 r                      #For each word, add them to the output in this way:
     i                  # Choose a character using this process:
       X·Ì              #  Get the last line of the output
          Y             #  And the current word
      [    ]¸           #  Join them with a space
             Ê>V?       #  If the resulting line is greater than the allowed length:
                ?R      #   Choose "/n" (newline)
                  :S    #  Otherwise choose " " (space)
     i                  # Add the chosen character to the output
  È+Y                   # Add the current word to the output
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes
```
.+$
$*
!`(?=\S.*¶(1)+)(?<-1>.)+(?=\s)
```
[Try it online!](https://tio.run/##RZBNTgMxDIX3PYWRuui0Q0QX7IBeAFClblngJu7UUn6mcdKjcQAuNjj9EVIWifP8/D5nKhxxmsxqPpsvZw/fi83r184sf38W627VLTYvj@s3061aWbppek@ZAvAoNYBLPmUQLoCBSg82RSFbqNQM6HhksRwHIM/FwI4c0EAFKGMBr7oqBj5S3jOEdno4ZJWz9wiiYqnaPqp51UqwKY@UeyiZpfCpEqhLwKrPu0tMUSOEkFyCyPujgS15T7GQNP0R91wwatdF/W8kFC9pQMNFul0CepKKDuGgcAJoQbEUqUFIQbkSaQhGW73W72G2GUktdSnqHADrUMnAZ6O4YYPgyBR7/bNFN6jjYTxippIRqCokR8uuNg8LjjFch3keqppgtqpBr@ExwKnq7HPb8b3Ua4uOCXDGzI1GF25mz09/ "Retina 0.8.2 – 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.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
Ｎθ←Ｆ⪪Ｓ «¿‹⁺ＬιⅈθＭ→⸿ι
```
[Try it online!](https://tio.run/##RVKxrtswDJxfvoLIJAOu0aVL@wUF0oegWTp0YWTaJiDJjihlKfrt7il5QQFDIKnj8Y6yXzj7lcO@f09bLe81XiW7W/ft8GO9i/t6kqkgmdZM7rIFLe6Bu5SsaXZdT0c6dh39ObzpRO4kZu4cqiFKc1mcAvHLdThvQD0pf@q8NM43CSZ0BlFxx9/52ErPTBH@3fcvnw@nNUsk3axGGtcAFaaFOErpya/JxBcpNROPuql5aCKByIEuMpLMUkgyFwrAVRsgIF@VYvt6mpoFDYHJALaK9g3kFZXo17xJ7gk2reitCoElckX6YklrgoQY13GlpNdloLOEIKmINfzCVy2c0PVA/ycySQ81BHFJPoLIQazyyDTBnBF7gi1YaiassD0dQYSyrwH1l5hzZgEllgLmSFznKgO9Nxcftsl4U0k97nzBBjGeNjy7lMwkFSY1eR1r4/A0KsfnsKBzBQn@D2A4QDxHulXMvrcdv0o9WjAm0p2zNjdY@LB/uod/ "Charcoal – Try It Online") Link is to verbose version of code. Takes input of `n` and `s` on separate lines. Explanation:
```
Ｎθ
```
Input `n`.
```
←
```
Move the cursor left one square to balance the right movement from the first iteration of the loop.
```
Ｆ⪪Ｓ «
```
Split the string on spaces and loop over the words.
```
¿‹⁺Ｌιⅈθ
```
Calculate whether the next word will reach the right edge.
```
Ｍ→
```
If it will not then move one square right.
```
⸿
```
If it will then start a new line.
```
ι
```
Output the word.
[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)
```
[Answer]
# [Red](http://www.red-lang.org), 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!](https://tio.run/##RZDNbhsxDITvfYrB9pKgziY59LKH9AXaImiPiy1AS1ybgP4sSkEL9N1dbmyjgCBIFDUzHyv78w/28/Jhnc5rT25WpGX2E55QqCpDZ0p/5pYHDGWyLZc2X65/0TI4@eU03cl69/CMB3h8giTPv7/gdP@CNJfH5wkfh1@Pg2leX8pyvyyLLudSJTWsGL7myhFStEf4HHKFSgNFbju4nJRd49YryEsRdZIO4CBtxE/24AM3cKWGYH1dR3zLdS@I29phNZODhEBQa9Zu34uJd6tEl2vhukOrok1OnWEqkbpdbyopJ4sQY/YZSfbHEa8cAqfGuvUfaS@NjCK@d/8XUk7vaWDhEl8PkQJrJ09YDU5BDoZlSBuENtILkYUQcj1Y/RbmtRKbpA3FlCOoHzqP@L5RXLGhVITTzt5cswmaPcqRKrdK4G6Qkpz4vmk4eKF4MQty6CZC1VkPBQtPEadu3m/bjG@lnX0xm4g3qrLR2MDHAZ@fzv8A "Red – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
õs#vDy«g²›i,}yðJ}?
```
[Try it online.](https://tio.run/##RZA9TgMxEIV7TjES7WpFQ01DhQBF4gQT72Qzkn82HjtSikjchwYh0VAmN@Eiy3N@hOTCHr95875JxkuVeT5@2@32cXf4GA9fv@8/2u13x8@n/cM8P6csgXSyGmhIPmUyLcRBSkcuRRNXpNRMPOik5jSOJF5LT28ykIxSSDIX8tBV6@kl5aVSaKejVYZcvWcyiK2ifYJ5RSW4lCfJHZWsVnRTheASuOJ5dYkpIkIIaUgUdbnuaSHeSyxiTb8GWuGIrpP638gkntIQwkW5XAJ7scoD0wpwRuwIWEBqEFbYzkQIoeyqR/0aZpFZYImlwDkQ17FKT6@N4oJNxpNK7PDnCjaI8TStOUvJTFIBqdHpUJuHo0E5nId5HStMODto2CM8B9pUzN62HV9LHVowJtCWszYaLLy/ub/7Aw)
**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)
```
[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.](https://tio.run/##fVFNi9swEL3nVww@2dgRe@nJ6xwLhW5ZyDHNYSLLyaT68EqjwBLy29PRxqG3gsHSzNOb996c8YLr8/jnri2mBG9I/roCSIxMGs7SVZnJqil7zRS8@r4cXn94NkcTu/@CthzJHzt4/DcbmGC4@/UmrTfXRw3iUFXddrcfkkqzJa4rqJqOh9hPIdbkGWh46el1q6zxRz71DU11ze12R/tmqdXNxjfX2A7cVr991bNw9jdjkwFuB0G27b4V3j4aztFDbLm/3fuVOJ3zwYrTxfAl0AhOQqgf6nZ7wKYEArD9TGycCpnVLC22vp4UzrP9rL@9NMup@hmicUBzyg7GYEOERAzoDHegg09Gc5EAONJMSZcAjJhWsDUjSJ4MJiKDFVxOCt5CPBC48nUwFUVkLUIScMryfBbyLBWnQ5zLMkR1YvrIBoTFYZbrk8UHLxKcC2MAT4eTgndjJT82qeBPeCBGidt9of8RJeO/1ICI82Y5OLQmZRwRJjGXADWILbFUTEiY6eFIRBDqbKX@FPMe0QilhCLMDjAfs1Hwq7hYbEPCmYzvpKdZEpTxMJ9QdhcRTBaT5DWNuXBoGAndY5ilYxYSjFowaEU8OvjIMvtSMn6WOnkiYxxcMFJxI4Grqml6WfNtdbv/BQ)
**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
```
[Answer]
# JavaScript, 40 bytes
```
s=>n=>eval(`s.match(/.{1,${n}}( |$)/g)`)
```
[Try it online!](https://tio.run/##RZBLbsMwDESvQgRZ2ICrtIsukxO0RYBeIIzE2Cz0cUTJmzRnd@l8UEALiRoO5/EHJxSbeSwvMTmaT9tZtru43dGEvjmICVjs0GzM5a1bX@L12sDvut307aGdbYqSPBmf@ubUrD5SpgA8Sg3gkk8ZhAtgoNLBIiVbqNQM6HhksRx7IM/FwDc5oJ4KUMYCXnVVDHymfGQIy@nglFXO3iOIiqVq@6jmVSvBpjxS7qBklsLnSqAuAas@ny4xRY0QQnIJIh8HA3vynmIhWfQDHrlg1K6b@t9IKN7SgIaL9LgE9CQVHcJJ4QTQgmIp0gIhBeVOpCEYbfVaf4bZZyS11KWocwCsfSUDXwvFAxsER6bY6Z8tukEdD@OAmUpGoKqQHC27unhYcIzhPsxzX9UEs1UNeg2PAc5VZ0/Ljp@lTlt0TIAJMy80unCzapv317ad/wA "JavaScript (Node.js) – Try It Online")
[Answer]
Thanks to @Erik the Outgolfer, a golfed version :
# [Python 3](https://docs.python.org/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!](https://tio.run/##RVLLTuNAELzzFaVcsLWORcTNyH8ACGmPUQ6dcTtuaR5mpofd/frQBqKVfLB7qqqrarz@0yXFx6vyX2WM2D2nzAGylhowJZ8yiigosHZwKRZ2ylozaJJVipN4AXvRHr95Al9YwZkU3nC19HhJ@SwI29NhzgYX7wnFwKUafTXxapPgUl45d9AsReW9MkwlULXPm0pM0SyEkKaEKOelxxt7z1G5bPiFzqIUjfWF/i9UOH65gZmL/PMSyHOpNBFmC1dADhbLIm0hilL5TmQmhFz1Nr@ZecvEJmmlmHIA1UvlHq9bip/YKLQKx87OnFqDth7rQpk1E7haSIlOprppOExC4XuZl0s1EcrOMOTNPAW8V9v9sXV8G3VGsTUBH5RlS2OF9zvcRbu/x4frxDPmRrvYDnf4s4hn6CBj/NXoMUhsrLFG2/3BAKdx3GGX8l6PcX8Yhv3h1M8Sp@Ye9237tNp9qbEGObVPOupRhtPVpLd/xdjXTw "Python 3 – Try It Online")
~~# [Python 3](https://docs.python.org/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!](https://tio.run/##RZJBj5tADIXv@RUWlwWVoEZ7Q@IftNVKPdIcHHASr2YMO@PZtr8@fWw2qsQBPM@f3/Ow/vXrYs83lz8uNFD1bUkSSddcIs1LWBJldeIo3tK0WJbJxUsinnXVPKldSIJ6Rz9lJrmIkyR2CtCV3NH3JZ2U4va0dE6QawhMGeJc0L4CXlCJ05JWSS150uz6VoRAiVzw@aDYYrAQ4zIvZHq6dvQiIYi55E1/5ZM6G7o@1P9BWezDDcGcyedL5CC58Mx0RrhMPBFiIdIWIjvneyKYUJ5KQP1h5iWxAImlgByJy6VIRz@2FJ@xKfOqYi3OJscGMZ7WKyfxxCQFIdUmncvGmGhWjvdhQS8FEE4TNBxgniO9Fcx@33b8KLVowZhI75x0S4OFdxXtDPf3/PU2y5nOtbfW9DsKw3jc0e@rBoE5q30rkg617X3s7Tj2/f5w7M5qc/1ET01rXw7N6GNUq@/6/QGk4zBUVIFEoeN1FajRrscGFR981L7HYdr@DKNwW3HRXle/rOpeF5BgZ/u/AGqa2z8 "Python 3 – Try It Online")
Not so golfed version...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ḲŒṖK€€ḣ€ƑƇṪY
```
[Try it online!](https://tio.run/##y0rNyan8///hjk1HJz3cOc37UdMaIHq4YzGQPDbxWPvDnasi////n6iQpJCskJKappCukJ6hkPXfFAA "Jelly – Try It Online")
Unfortunately, this is too slow to work for the provided test case in under a minute over TIO.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 162 bytes
```
string[]t(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!](https://tio.run/##VVJLa9xADD6vf4UwgXgSx00PPTlLCqU9JSV0Az00LWjHilcwD2ceIWXj377VZHdpa@bg0UjfQ5KOF9oH2u1yZDfC6ndMZPvq31t3Ty@p@0ZjNhg@v0yBYmTvYl8tyldNeW1YgzYYI9wFPwa01bZaxIRJ4jGFghWX9Y0QWeApZguDNz5A5ARoKbWgBZB0opQD4MATR12qyHDqYEUD0EgJKGACI3k5dnDrw5rBltPCYyFhYxCiJMcs5ZOAZ4lYMThRaEGExMRPmUBQLGa5HlGcdyLBWj94cLzedHBHxpBLFEv@Btec0EnVW/ZfoEjuTQ2IOEeHH4uGYsYB4VHMRUANYkssFRPSlbh3JCIYdTYSP4q5C0gCKU0RZAuYx0wdfC0uDrYh4sTkWnnTSToo9DBtMFAKCJTFJDvNQy4YGgZGuyczXMYHGLTkoBHxaOEpC/dz6fEx1EqJ0Fh4xsDFjTS8q/uqWhymfBjqs@cBbpFdo6qFzHrxKLNFvWmkDjSwg9TE9sOlUmVJPslwvaHue@BEN@yo0Uq2Z67@B91vyo@fUrrfGddy8aG2BXVc1nUvNE2J8fKy5/Pzq1tMm@6L8RJuBi9opFx3Q25Mm3eoejWeL0/qX912u@UzvHg/z/Nr3YeyZQ5ko@mlW01iv3Htyce6uXaqub5aNtuxuw9sm9PXUzWrh9WZeoi16ud5t/sD "C# (.NET Core) – 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](http://regexstorm.net/tester?p=%28%3f%3c%3d%28%5e.%7b49%7d%7c%5e.%7b99%7d%7c%5e.%7b149%7d%7c%5e.%7b199%7d%7c%5e.%7b249%7d%7c%5e.%7b299%7d%7c%5e.%7b349%7d%7c%5e.%7b399%7d%29%5cS*%29%5cs&i=Lorem+ipsum+dolor+sit+amet%2c+consectetur+adipiscing+elit.+Sed+eget+erat+lectus.+Morbi+mi+mi%2c+fringilla+sed+suscipit+ullamcorper%2c+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%2c+auctor+nec+pharetra+eu%2c+tincidunt+ac+diam.+Sed+ligula+arcu%2c+aliquam+quis+velit+aliquam%2c+dictum+varius+erat.&o=n)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 78 bytes
```
s=>n=>System.Text.RegularExpressions.Regex.Replace(s,".{1,"+n+"}( |$)","$0\n")
```
[Try it online!](https://tio.run/##RVJNb9swDL3nVzwYPdioZqyHnbrk1p3aoVgH7LILIzMJAUl2RanIsO23Z1TSYIBgiDT5Pkh5/eBVTl9q8p@1ZEl7d75LKu4SbzbYYX3S9SatNy@/tHAcv/OxjN94XwPlh@OSWVXmpC3FR/sugTz36rrx953rbtNt97fHn5uhc93Nx5@pG073q9Xqgg/FGt3jnDlCFq0R0xzmDJUCilwcvEGzL1xqBk2yiPrWx0HKiBeeYKwFnKkgWF3VEU9z3gpiOw67RiMhENSKtVr7YuDVMtHPeeHsYFK0yGtlGEqkauEVJc3JJMQ4TzOSbA8jnjkEToW11R9oK4WSdZ2r/wMpp7MamLjE75dIgbXSRNiZOQV5mC2z1ExoIb04MhFCvgbLX8U8Z2KDtKEYcgTVfeURX5uLd9tQWoSTs3@@2ASNHsuBMpdM4GomJXmZasPwmITihSxIWyQoe6uhYOIp4rUa91ub8TXlrMVoIt4oS3NjAx87W6S9FSRb4t0nC35kKdzveh36NAz3p38 "C# (Visual C# Interactive Compiler) – Try It Online")
Credit goes to @LukeStevens for coming up with the Java version... Apparently .NET makes you import the `RegularExpressions` namespace in order to do a replace :(
Here is my original version that splits on the space character and uses LINQ to join them back together:
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 91 bytes
```
s=>n=>s.Split(' ').Aggregate((a,w)=>a+(a.Length-a.LastIndexOf('\n')+w.Length>n?'\n':' ')+w)
```
[Try it online!](https://tio.run/##RVI7b9wwDN7vVxBZzsY5BjJ0SWoXXQoUSNoAGbp04cm0j4BEOaKU67@/UPdAAQ0kRX4PSk7vnfLpRxH3VXNiWbpzzJK7Sz6OMMNw0mGUYdT@bfWcmy1s2/77siRaMFPTYHdshxF3DfbPJEs@3FuAmn/KRP9@z832r2zb3fF6Ocq3WnisKLtje3rabDYXMlAY4O45JgrAq5YAU/QxgXIGDJQ7cFGUXKZcEuDEK6urc2SqenijCWihDJQwg7e@oj28xLRnCPV0MFca9h5BrVmLja8GXqwSXEwrpQ5MimZ@LwSGErBYekORKCYhhDhFEN4fengl70kyae0/4J4zik2du/8DKclZDZg4oWsQ0JMWnBBmM6eADsyWWaomNKNeHJkIRle81W9iXhOSQdpSDDkAlqVQD7@qi6ttUFyZpLM7l22DRg/rARPlhEDFTLI4nkrFcDAxhguZ56UYCCZnPehNPAZ4L8b9UXd8K3U2YjQBPjBxdWML7@/sIe3jgNgjPnyx5E9i@x1zo20jbft0@gQ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Dart](https://www.dartlang.org/), 112 bytes
```
f(s,n){var l=[''];s.split(' ').forEach((w){if((l.last+w).length<=n)l.last+=w+' ';else l.add(w+' ');});return l;}
```
[Try it online!](https://tio.run/##RVK7buMwEOz9FdNJQgQiKa7SubwudwiQUlCxplbyAiSl8BEXhr/dt3JsGBAEajU7OzPLkWK@Xqc6taE5f1OE2/dVNXTJpNVJritUjZmW@Ifssa5PzVmmunbGUcovp8Y4DnM@/t6H5l7bn160pWOXGM7QONa3QtNdmi5yLjHAdZerJwl1c94B28yMPXo9A331vkT2kDUVj3FxS0SSDPKcW9glJLZ5owGNskqyEmawCjX45BE8cwZHynCKK8ng7xIPAr89LaaocHGOkBSciravSl604u0SV44tcpSU5aswlMVT0c8HS1iCSvB@GRcEORwNPthpApnThj/SQTIF7bqhn0SJw00NVFzg@8GT41RoJExqLoEs1JZa2kykTOnHkYoQssVp/SHmIxIrpYaizB5U5sIG/zYXd9tItAqHVv/ZrAnqeKxH0vwjgYualGBlLBuHxSjkf4Y5mYuSULSKIafiyeOr6OzvLeNHqdUWHeO33cnmRgM3VfvrddAdDt1O3/l5Z8ptzcBUl/51aEv/Njxv1KobyU2nAL0fu8v1Pw "Dart – Try It Online")
[Answer]
# APL(NARS), 48 chars, 96 bytes
```
{⊃⍵{⍺≥≢⍵:⊂⍵⋄k←1+⍺-' '⍳⍨⌽r←⍺↑⍵⋄(⊂k↑r),⍺∇k↓⍵}⍨⍺+1}
```
test:
```
  f←{⊃⍵{⍺≥≢⍵:⊂⍵⋄k←1+⍺-' '⍳⍨⌽r←⍺↑⍵⋄(⊂k↑r),⍺∇k↓⍵}⍨⍺+1}
  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."
  50 f 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.                                              
```
[Answer]
# C, 63 bytes
```
b(a,n)char*a;{while(strlen(a)>n){for(a+=n;*a-32;--a);*a++=10;}}
```
The function of this exercise b(a,n) would break the line "a" as exercise said,
in the way not change its length (if we see the result as one string) because
change some spaces in \n or new line in place. The input string "a" should have no \n character too in it for b() function (it could have \n in input string for bs())
b(a,n) function would be ok only because the restriction of this exercise,
that impose each word of "a" string has length < n if this is not true, that function can go  
to one infinite loop...(very wrong in my way of see so i copy too the function more good because
in that case would return -1 and not would go to one infinite loop; it is bs(a,n) below)I not exclude both functions are bugged...
```
#define R(x,y) if(x)return y
#define U unsigned
U bs(char*a,U n)
{U c,q,r=1,i,j;
 R(!a||n<1||n++>0xFFFF,-1);
 for(j=c=i=0;;++i,++c)
    {R(i==-1,-1);q=a[i];
     if(q==10)goto l;
     if(c>=n){R(i-j>n,-1);a[i=j]=10;l:c=-1;++r;}
     R(!q,r);
     if(q==32)j=i;
    }
}
```
result of b() passed on one function that add line lenght each line
```
Lorem ipsum dolor sit amet, consectetur adipiscing [50]
elit. Sed eget erat lectus. Morbi mi mi, fringilla [50]
sed suscipit ullamcorper, tristique at mauris. [46]
Morbi non commodo nibh. Pellentesque habitant [45]
morbi tristique senectus et netus et malesuada [46]
fames ac turpis egestas. Sed at iaculis mauris. [47]
Praesent a sem augue. Nulla lectus sapien, auctor [49]
nec pharetra eu, tincidunt ac diam. Sed ligula [46]
arcu, aliquam quis velit aliquam, dictum varius [47]
erat. [5]
```
]