View Problem

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "

Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
DiskEdit
clojure
(defn string-wrap [s]
(if (= 0 (count s))
nil
(lazy-seq (cons (apply str (take 78 s))
(string-wrap (drop 78 s))))))

(let [s (apply str (repeat 10 "The quick brown fox jumps over the lazy dog. "))]
(doseq [line (string-wrap s)]
(println "> " line)))
DiskEdit
clojure
(defn wrap
"the expected output shown wraps at 77, rather than 78"
[s]
(if (empty? s)
nil
(cons (apply str (take 77 s))
(wrap (drop 77 s)))))

(->> (repeat 10 "The quick brown fox jumps over the lazy dog. ")
(apply str)
(wrap)
(map #(println "> " %)))
DiskEdit
cpp
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

void rep(ostream &os, const string& str, int times)
{
while (times--)
os << str;
}

void wrap(ostream &os, const string& str, const string &prefix, int width)
{
for (int offset = 0; offset < str.size(); offset += width)
os << prefix << str.substr(offset, width) << endl;
}

int main()
{
stringstream input;

rep(input, "The quick brown fox jumps over the lazy dog. ", 10);
wrap(cout, input.str(), "> ", 78);
}
DiskEdit
erlang
wrapper(String, Times, Length) ->
StrList = lists:reverse(formatter(string:copies(String, Times), Length, [])),
lists:foreach(fun(Str) -> io:format("~p~n", [Str]) end, StrList).

formatter([], _Length, Acc) -> Acc;
formatter(String, Length, Acc) when length(String) > Length - 1->
{Head, Tail} = lists:split(Length - 1, String),
formatter(string:strip(Tail), Length, [[$>, $ | Head] | Acc]);
formatter(String, Length, Acc) ->
formatter([], Length, [[$>, $ | String] | Acc]).
ExpandDiskEdit
fantom
s:=Str[,].fill("The quick brown fox jumps over the lazy dog. ",10).join
while(s.size>0){
echo("> "+s[0..(77.min(s.size))-1])
s=(s.size>77)?s[77..-1].trim : ""
}
DiskEdit
go 1.0.3
package main

import (
"fmt"
"strings"
)

func main() {
str := "The quick brown fox jumps over the lazy dog. "
chs := strings.Split(str, "")
j := 1
for i := 0; i < 10; i++ {
for n, l := 0, len(chs); n < l; n++ {
if j == 1 {
fmt.Print("> ")
}
fmt.Print(chs[n])
if j == 77 {
fmt.Println()
j = 1;
}else {
j++;
}
}
}
}
DiskEdit
go 1.0.3
package main

func main() {
chs := []rune("The quick brown fox jumps over the lazy dog. ")
j := 1
for i := 0; i < 10; i++ {
for _, v := range chs {
if j == 1 {
print("> ")
}
print(string(v))
if j == 77 {
println()
j = 1;
}else {
j++;
}
}
}
}
DiskEdit
groovy 1.8.0
'The quick brown fox jumps over the lazy dog. '.multiply(10).split('(?<=\\G.{76})').each{println '> ' + it}
DiskEdit
groovy
st = "The quick brown fox jumps over the lazy dog. " * 10
width = 76
while(st){
(first, st) = st.length() > width? [st[0..width], st[(width+1)..-1].trim()] : [st, null]
println "> $first"
}
DiskEdit
haskell
wrap str
| length str <= 77 = [str]
| otherwise = [take 77 str] ++ wrap (drop 77 str)

mapM_ putStrLn . map ("> " ++) . wrap . concat . replicate 10 $ "The quick brown fox jumps over the lazy dog. "
DiskEdit
haskell
tenTimes = concat . replicate 10 $ "The quick brown fox jumps over the lazy dog. "
warp n = takeWhile (/="") . unfoldr (Just . splitAt n)
main = mapM_ (putStrLn . ("> " ++)) $ warp 77 tenTimes
DiskEdit
haskell
mapM_ (putStrLn . ("> " ++)) $ takeWhile (/="") . unfoldr (Just . splitAt 77) . concat . replicate 10 $ "The quick brown fox jumps over the lazy dog. "
DiskEdit
java
public class SolutionXX {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
String words = "The quick brown fox jumps over the lazy dog. ";

for (int i = 0; i < 10; i++)
{
builder.append(words);
}

String toWrap = builder.toString();
int width = 76;
while (toWrap!=null && toWrap.length()>0)
{
String first = toWrap.length() > width ? toWrap.substring(0, width+1) : toWrap;
toWrap = (!toWrap.equals(first)) ? toWrap.substring(width + 1).trim() : null;
System.out.println("> " + first);
}

}
}
DiskEdit
java 1.5+
public class PangramWrapper {
public static void main(String[] args) {
int lineLimit = 78;
String newLine = "\n> ";
String pangram = "The quick brown fox jumps over the lazy dog. ";
String repeated = new String(new char[10]).replace("\0", pangram);

StringBuffer all = new StringBuffer(newLine + repeated);
for(int count = 1; count*lineLimit < all.length(); count++) {
all.insert(count * lineLimit, newLine);
}
System.out.println(all);
}
}
DiskEdit
java 1.8 (join)
public class PangramWrapperViaRegexAndJoin {
public static void main(String[] args) {
String newLine = "\n> ",
pangram = "The quick brown fox jumps over the lazy dog. ",
repeated = new String(new char[10]).replace("\0", pangram);

final String[] splitted = repeated.split("(?<=\\G.{78})"); // worse performance than substring in for-loop
System.out.println("> "+ String.join(newLine, Arrays.asList(splitted)));
}
}
DiskEdit
ocaml
let wrapper margin =
let cur = ref 0 in
fun word ->
let len = String.length word in
let beginning_of_line () =
Printf.printf "> %s" word;
cur := len + 2 in
if !cur = 0 then
beginning_of_line ()
else begin
cur := !cur + 1 + len;
if !cur <= margin then
Printf.printf " %s" word
else begin
print_newline ();
beginning_of_line ()
end
end

let wrap_string wrapper s =
let len = String.length s in
let rec aux_out i =
if i < len then
match s.[i] with
| ' ' | '\t' | '\n' ->
aux_out (i+1)
| _ -> aux_in i (i+1)
and aux_in i0 i =
if i >= len then
wrapper (String.sub s i0 (len - i0))
else match s.[i] with
| ' ' | '\t' | '\n' ->
wrapper (String.sub s i0 (i - i0));
aux_out (i+1)
| _ ->
aux_in i0 (i+1) in
aux_out 0

let () =
let base_string = "The quick brown fox jumps over the lazy dog. " in
let w = wrapper 78 in
for i = 1 to 10 do
wrap_string w base_string
done;
print_newline ()
DiskEdit
perl
print map"> $_\n",("The quick brown fox jumps over the lazy dog. " x 10)=~/(.{1,77}) ?/g;
ExpandDiskEdit
php
foreach(str_split(str_repeat("The quick brown fox jumps over the lazy dog. ", 10), 77) as $line)
printf("> %s\n", trim($line));
DiskEdit
python
def wrap(string, length):

while len(string):
print("> " + string[0:length - 1])
string = string[length - 1:].strip()


wrap("The quick brown fox jumps over the lazy dog. " * 10, 78)
DiskEdit
ruby 1.8.7
str = "The quick brown fox jumps over the lazy dog. " * 10
outarr = str.scan(/[^ ].{0,76}/)
outarr.each{ |line| puts "> %s" % line }
DiskEdit
scala
object Wrap {
def wordWrap(str: String, width: Int, lineStart: String, reps: Int) = {
var strRepeated = ""
for(i <- 0 until reps) strRepeated += str
while(strRepeated.length > width) {
println(lineStart + strRepeated.substring(0, (width-1)))
strRepeated = strRepeated.substring(width)
}
println(lineStart + strRepeated)
}

def main(args: Array[String]) = {
wordWrap("The quick brown fox jumps over the lazy dog. ", 78, "> ", 10)
}
}
DiskEdit
scala
def stringWrap(s: String): List[String] =
if (s.length == 0) Nil else s.take(78) :: stringWrap(s.drop(78))

stringWrap("The quick brown fox jumps over the lazy dog. " * 10).foreach(line => println("> " + line))
DiskEdit
scala
("The quick brown fox jumps over the lazy dog. " * 10) grouped(78) foreach { line => println("> " + line) }

Submit a new solution for clojure, cpp, erlang, fantom ...