Make a simple word wrapper
up vote
15
down vote
favorite
(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
|
show 7 more comments
up vote
15
down vote
favorite
(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
Format a list of words
– user202729
2 days ago
2
n is the max line length ? or the length we have to reach before line break ?
– david
yesterday
1
@david, or the number of lines?
– Peter Taylor
yesterday
1
28 bytes Python is it relevant?
– david
yesterday
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
yesterday
|
show 7 more comments
up vote
15
down vote
favorite
up vote
15
down vote
favorite
(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
(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
code-golf string
edited yesterday
asked 2 days ago
ATMunn
1067
1067
Format a list of words
– user202729
2 days ago
2
n is the max line length ? or the length we have to reach before line break ?
– david
yesterday
1
@david, or the number of lines?
– Peter Taylor
yesterday
1
28 bytes Python is it relevant?
– david
yesterday
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
yesterday
|
show 7 more comments
Format a list of words
– user202729
2 days ago
2
n is the max line length ? or the length we have to reach before line break ?
– david
yesterday
1
@david, or the number of lines?
– Peter Taylor
yesterday
1
28 bytes Python is it relevant?
– david
yesterday
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
yesterday
Format a list of words
– user202729
2 days ago
Format a list of words
– user202729
2 days ago
2
2
n is the max line length ? or the length we have to reach before line break ?
– david
yesterday
n is the max line length ? or the length we have to reach before line break ?
– david
yesterday
1
1
@david, or the number of lines?
– Peter Taylor
yesterday
@david, or the number of lines?
– Peter Taylor
yesterday
1
1
28 bytes Python is it relevant?
– david
yesterday
28 bytes Python is it relevant?
– david
yesterday
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
yesterday
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
yesterday
|
show 7 more comments
21 Answers
21
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.
add a comment |
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
add a comment |
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!
add a comment |
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}
$$
Trailing spaces are allowed. mayber+w+' '
?
– l4m2
7 hours ago
add a comment |
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!
1
Explanation:DJ:
: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]
– Erik the Outgolfer
yesterday
add a comment |
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
add a comment |
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!
add a comment |
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!
1
Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
– ATMunn
yesterday
add a comment |
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.
add a comment |
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.
add a comment |
up vote
1
down vote
Japt, 25 bytes
¸rÈ·Ì+S+Y Ê>V?X+R+Y:X+S+Y
Try it online!
Pretty straightforward. I'm certain there's a more concise way to do this than having "X+R/S+Y" three times, but my alternatives have all been longer.
Explanation:
¸ :Split into words
r :Reduce back into a string by:
È : 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:
X+R+Y : Use a newline before the next word
: : Otherwise:
X+S+Y : Use a space before the next word
24 bytes with[X,Y].join(...)
.
– Bubbler
2 hours ago
add a comment |
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!
add a comment |
up vote
1
down vote
JavaScript, 39 bytes
s=>n=>eval(`s.match(/.{1,${n}} |.+/g)`)
Try it online!
Fail at the end
– l4m2
2 hours ago
@l4m2 fixed....
– tsh
2 hours ago
add a comment |
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
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♦
yesterday
On a side note, only full programs and functions are allowed by default.fold -sw$1
(orfold -s$1
) would comply with that rule.
– Dennis♦
yesterday
add a comment |
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...
1
Some golfs. (prints to STDOUT, doesn't return).
– Erik the Outgolfer
yesterday
add a comment |
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)
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
yesterday
@Neil Nice use ofch
units. Firefox 65 computes50ch
as500px
; Chromium 70 computes50ch
as400px
– guest271314
yesterday
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
yesterday
I was able to tweak my original suggestion to work in Chrome by putting the<p>
inside the<tt>
.
– Neil
yesterday
1
next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
– Neil
yesterday
|
show 1 more comment
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!
add a comment |
up vote
0
down vote
Powershell, 40 bytes
param($s,$n)$s-replace"(.{0,$n}) ",'$1
'
Note: The regexp uses a space as a separator because the author posts the yes
on the question Are spaces the only characters that divide words?
. The reqexp should be (.{0,$n})s
if any whitespace allowed.
Test script:
$f = {
param($s,$n)$s-replace"(.{0,$n}) ",'$1
'
}
@(
,(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.
"@)
) | %{
$n,$s,$expected = $_
$result = &$f $s $n
$result-eq$expected
# $result # uncomment this line to dispaly a result
}
Output:
True
add a comment |
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.
add a comment |
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.
add a comment |
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
add a comment |
21 Answers
21
active
oldest
votes
21 Answers
21
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.
add a comment |
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.
add a comment |
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.
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.
edited yesterday
answered yesterday
Erik the Outgolfer
30.9k429102
30.9k429102
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited 22 hours ago
answered 2 days ago
Jo King
19.8k245105
19.8k245105
add a comment |
add a comment |
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!
add a comment |
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!
add a comment |
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!
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!
edited 2 days ago
answered 2 days ago
Davіd
4258
4258
add a comment |
add a comment |
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}
$$
Trailing spaces are allowed. mayber+w+' '
?
– l4m2
7 hours ago
add a comment |
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}
$$
Trailing spaces are allowed. mayber+w+' '
?
– l4m2
7 hours ago
add a comment |
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}
$$
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}
$$
edited yesterday
answered 2 days ago
Arnauld
70.3k686295
70.3k686295
Trailing spaces are allowed. mayber+w+' '
?
– l4m2
7 hours ago
add a comment |
Trailing spaces are allowed. mayber+w+' '
?
– l4m2
7 hours ago
Trailing spaces are allowed. maybe
r+w+' '
?– l4m2
7 hours ago
Trailing spaces are allowed. maybe
r+w+' '
?– l4m2
7 hours ago
add a comment |
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!
1
Explanation:DJ:
: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]
– Erik the Outgolfer
yesterday
add a comment |
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!
1
Explanation:DJ:
: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]
– Erik the Outgolfer
yesterday
add a comment |
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!
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!
edited yesterday
answered 2 days ago
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
yesterday
add a comment |
1
Explanation:DJ:
: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]
– Erik the Outgolfer
yesterday
1
1
Explanation:
DJ:
: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]– Erik the Outgolfer
yesterday
Explanation:
DJ:
: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]– Erik the Outgolfer
yesterday
add a comment |
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
add a comment |
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
add a comment |
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
Haskell, 70 bytes
s!n|length s<=n=[s]|(t,_:d)<-splitAt(until((<'!').(s!!))pred n)s=t:d!n
edited yesterday
answered yesterday
Lynn
49.3k794226
49.3k794226
add a comment |
add a comment |
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!
add a comment |
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!
add a comment |
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!
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!
answered yesterday
Lynn
49.3k794226
49.3k794226
add a comment |
add a comment |
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!
1
Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
– ATMunn
yesterday
add a comment |
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!
1
Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
– ATMunn
yesterday
add a comment |
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!
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!
edited yesterday
answered yesterday
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
yesterday
add a comment |
1
Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
– ATMunn
yesterday
1
1
Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
– ATMunn
yesterday
Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.
– ATMunn
yesterday
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered yesterday
Neil
78.5k744175
78.5k744175
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered yesterday
Neil
78.5k744175
78.5k744175
add a comment |
add a comment |
up vote
1
down vote
Japt, 25 bytes
¸rÈ·Ì+S+Y Ê>V?X+R+Y:X+S+Y
Try it online!
Pretty straightforward. I'm certain there's a more concise way to do this than having "X+R/S+Y" three times, but my alternatives have all been longer.
Explanation:
¸ :Split into words
r :Reduce back into a string by:
È : 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:
X+R+Y : Use a newline before the next word
: : Otherwise:
X+S+Y : Use a space before the next word
24 bytes with[X,Y].join(...)
.
– Bubbler
2 hours ago
add a comment |
up vote
1
down vote
Japt, 25 bytes
¸rÈ·Ì+S+Y Ê>V?X+R+Y:X+S+Y
Try it online!
Pretty straightforward. I'm certain there's a more concise way to do this than having "X+R/S+Y" three times, but my alternatives have all been longer.
Explanation:
¸ :Split into words
r :Reduce back into a string by:
È : 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:
X+R+Y : Use a newline before the next word
: : Otherwise:
X+S+Y : Use a space before the next word
24 bytes with[X,Y].join(...)
.
– Bubbler
2 hours ago
add a comment |
up vote
1
down vote
up vote
1
down vote
Japt, 25 bytes
¸rÈ·Ì+S+Y Ê>V?X+R+Y:X+S+Y
Try it online!
Pretty straightforward. I'm certain there's a more concise way to do this than having "X+R/S+Y" three times, but my alternatives have all been longer.
Explanation:
¸ :Split into words
r :Reduce back into a string by:
È : 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:
X+R+Y : Use a newline before the next word
: : Otherwise:
X+S+Y : Use a space before the next word
Japt, 25 bytes
¸rÈ·Ì+S+Y Ê>V?X+R+Y:X+S+Y
Try it online!
Pretty straightforward. I'm certain there's a more concise way to do this than having "X+R/S+Y" three times, but my alternatives have all been longer.
Explanation:
¸ :Split into words
r :Reduce back into a string by:
È : 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:
X+R+Y : Use a newline before the next word
: : Otherwise:
X+S+Y : Use a space before the next word
answered yesterday
Kamil Drakari
2,636416
2,636416
24 bytes with[X,Y].join(...)
.
– Bubbler
2 hours ago
add a comment |
24 bytes with[X,Y].join(...)
.
– Bubbler
2 hours ago
24 bytes with
[X,Y].join(...)
.– Bubbler
2 hours ago
24 bytes with
[X,Y].join(...)
.– Bubbler
2 hours ago
add a comment |
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!
add a comment |
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!
add a comment |
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!
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!
edited 23 hours ago
answered yesterday
Galen Ivanov
6,01211032
6,01211032
add a comment |
add a comment |
up vote
1
down vote
JavaScript, 39 bytes
s=>n=>eval(`s.match(/.{1,${n}} |.+/g)`)
Try it online!
Fail at the end
– l4m2
2 hours ago
@l4m2 fixed....
– tsh
2 hours ago
add a comment |
up vote
1
down vote
JavaScript, 39 bytes
s=>n=>eval(`s.match(/.{1,${n}} |.+/g)`)
Try it online!
Fail at the end
– l4m2
2 hours ago
@l4m2 fixed....
– tsh
2 hours ago
add a comment |
up vote
1
down vote
up vote
1
down vote
JavaScript, 39 bytes
s=>n=>eval(`s.match(/.{1,${n}} |.+/g)`)
Try it online!
JavaScript, 39 bytes
s=>n=>eval(`s.match(/.{1,${n}} |.+/g)`)
Try it online!
edited 2 hours ago
answered 3 hours ago
tsh
8,09011346
8,09011346
Fail at the end
– l4m2
2 hours ago
@l4m2 fixed....
– tsh
2 hours ago
add a comment |
Fail at the end
– l4m2
2 hours ago
@l4m2 fixed....
– tsh
2 hours ago
Fail at the end
– l4m2
2 hours ago
Fail at the end
– l4m2
2 hours ago
@l4m2 fixed....
– tsh
2 hours ago
@l4m2 fixed....
– tsh
2 hours ago
add a comment |
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
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♦
yesterday
On a side note, only full programs and functions are allowed by default.fold -sw$1
(orfold -s$1
) would comply with that rule.
– Dennis♦
yesterday
add a comment |
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
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♦
yesterday
On a side note, only full programs and functions are allowed by default.fold -sw$1
(orfold -s$1
) would comply with that rule.
– Dennis♦
yesterday
add a comment |
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
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
edited yesterday
answered yesterday
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♦
yesterday
On a side note, only full programs and functions are allowed by default.fold -sw$1
(orfold -s$1
) would comply with that rule.
– Dennis♦
yesterday
add a comment |
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♦
yesterday
On a side note, only full programs and functions are allowed by default.fold -sw$1
(orfold -s$1
) would comply with that rule.
– Dennis♦
yesterday
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♦
yesterday
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♦
yesterday
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♦
yesterday
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♦
yesterday
add a comment |
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...
1
Some golfs. (prints to STDOUT, doesn't return).
– Erik the Outgolfer
yesterday
add a comment |
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...
1
Some golfs. (prints to STDOUT, doesn't return).
– Erik the Outgolfer
yesterday
add a comment |
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...
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...
edited yesterday
answered yesterday
david
647
647
1
Some golfs. (prints to STDOUT, doesn't return).
– Erik the Outgolfer
yesterday
add a comment |
1
Some golfs. (prints to STDOUT, doesn't return).
– Erik the Outgolfer
yesterday
1
1
Some golfs. (prints to STDOUT, doesn't return).
– Erik the Outgolfer
yesterday
Some golfs. (prints to STDOUT, doesn't return).
– Erik the Outgolfer
yesterday
add a comment |
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)
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
yesterday
@Neil Nice use ofch
units. Firefox 65 computes50ch
as500px
; Chromium 70 computes50ch
as400px
– guest271314
yesterday
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
yesterday
I was able to tweak my original suggestion to work in Chrome by putting the<p>
inside the<tt>
.
– Neil
yesterday
1
next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
– Neil
yesterday
|
show 1 more comment
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)
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
yesterday
@Neil Nice use ofch
units. Firefox 65 computes50ch
as500px
; Chromium 70 computes50ch
as400px
– guest271314
yesterday
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
yesterday
I was able to tweak my original suggestion to work in Chrome by putting the<p>
inside the<tt>
.
– Neil
yesterday
1
next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
– Neil
yesterday
|
show 1 more comment
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)
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)
edited yesterday
answered 2 days ago
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
yesterday
@Neil Nice use ofch
units. Firefox 65 computes50ch
as500px
; Chromium 70 computes50ch
as400px
– guest271314
yesterday
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
yesterday
I was able to tweak my original suggestion to work in Chrome by putting the<p>
inside the<tt>
.
– Neil
yesterday
1
next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
– Neil
yesterday
|
show 1 more comment
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
yesterday
@Neil Nice use ofch
units. Firefox 65 computes50ch
as500px
; Chromium 70 computes50ch
as400px
– guest271314
yesterday
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
yesterday
I was able to tweak my original suggestion to work in Chrome by putting the<p>
inside the<tt>
.
– Neil
yesterday
1
next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
– Neil
yesterday
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
yesterday
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
yesterday
@Neil Nice use of
ch
units. Firefox 65 computes 50ch
as 500px
; Chromium 70 computes 50ch
as 400px
– guest271314
yesterday
@Neil Nice use of
ch
units. Firefox 65 computes 50ch
as 500px
; Chromium 70 computes 50ch
as 400px
– guest271314
yesterday
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
yesterday
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
yesterday
I was able to tweak my original suggestion to work in Chrome by putting the
<p>
inside the <tt>
.– Neil
yesterday
I was able to tweak my original suggestion to work in Chrome by putting the
<p>
inside the <tt>
.– Neil
yesterday
1
1
next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
– Neil
yesterday
next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js
– Neil
yesterday
|
show 1 more comment
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!
add a comment |
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!
add a comment |
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!
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!
answered yesterday
dana
25114
25114
add a comment |
add a comment |
up vote
0
down vote
Powershell, 40 bytes
param($s,$n)$s-replace"(.{0,$n}) ",'$1
'
Note: The regexp uses a space as a separator because the author posts the yes
on the question Are spaces the only characters that divide words?
. The reqexp should be (.{0,$n})s
if any whitespace allowed.
Test script:
$f = {
param($s,$n)$s-replace"(.{0,$n}) ",'$1
'
}
@(
,(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.
"@)
) | %{
$n,$s,$expected = $_
$result = &$f $s $n
$result-eq$expected
# $result # uncomment this line to dispaly a result
}
Output:
True
add a comment |
up vote
0
down vote
Powershell, 40 bytes
param($s,$n)$s-replace"(.{0,$n}) ",'$1
'
Note: The regexp uses a space as a separator because the author posts the yes
on the question Are spaces the only characters that divide words?
. The reqexp should be (.{0,$n})s
if any whitespace allowed.
Test script:
$f = {
param($s,$n)$s-replace"(.{0,$n}) ",'$1
'
}
@(
,(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.
"@)
) | %{
$n,$s,$expected = $_
$result = &$f $s $n
$result-eq$expected
# $result # uncomment this line to dispaly a result
}
Output:
True
add a comment |
up vote
0
down vote
up vote
0
down vote
Powershell, 40 bytes
param($s,$n)$s-replace"(.{0,$n}) ",'$1
'
Note: The regexp uses a space as a separator because the author posts the yes
on the question Are spaces the only characters that divide words?
. The reqexp should be (.{0,$n})s
if any whitespace allowed.
Test script:
$f = {
param($s,$n)$s-replace"(.{0,$n}) ",'$1
'
}
@(
,(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.
"@)
) | %{
$n,$s,$expected = $_
$result = &$f $s $n
$result-eq$expected
# $result # uncomment this line to dispaly a result
}
Output:
True
Powershell, 40 bytes
param($s,$n)$s-replace"(.{0,$n}) ",'$1
'
Note: The regexp uses a space as a separator because the author posts the yes
on the question Are spaces the only characters that divide words?
. The reqexp should be (.{0,$n})s
if any whitespace allowed.
Test script:
$f = {
param($s,$n)$s-replace"(.{0,$n}) ",'$1
'
}
@(
,(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.
"@)
) | %{
$n,$s,$expected = $_
$result = &$f $s $n
$result-eq$expected
# $result # uncomment this line to dispaly a result
}
Output:
True
edited 14 hours ago
answered 14 hours ago
mazzy
1,857313
1,857313
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited 11 hours ago
answered 12 hours ago
LegionMammal978
15k41752
15k41752
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered 10 hours ago
Erik the Outgolfer
30.9k429102
30.9k429102
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited 7 hours ago
answered 8 hours ago
Embodiment of Ignorance
1507
1507
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
Format a list of words
– user202729
2 days ago
2
n is the max line length ? or the length we have to reach before line break ?
– david
yesterday
1
@david, or the number of lines?
– Peter Taylor
yesterday
1
28 bytes Python is it relevant?
– david
yesterday
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
yesterday