View Subcategory

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
fantom
"reverse me".reverse

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
fantom
"This is a end, my only friend!".split.reverse.join(" ")

Text wrapping

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 "> ", yielding this result:

> 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
> 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
> 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
> quick brown fox jumps over the lazy dog.
fantom
buf := Buf()
10.times { buf.writeChars("The quick brown fox jumps over the lazy dog. ") }
buf.flip

out := Env.cur.out
sep := ">"; max := 72 - sep.size - 1
acc := 0; Str? s := null
while ((s = buf.readStrToken) != null)
{
if (acc == 0)
out.print(sep)

acc += s.size
if (acc > max)
{
out.print("\n$sep")
acc = s.size
}
out.print(" $s")
buf.readStrToken(4096) { !it.isSpace }
acc++
}

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
fantom
s := " hello ".trim

Simple substitution cipher

Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
fantom
rot := |Str s, |Int c -> Int| remap -> Str|
{
rs := ""
s.each { rs += remap(it).toChar }
return rs
}

rot13 := |Str s -> Str|
{
rot(s) |Int c -> Int|
{
lc := c.lower
c += (lc >= 'a' && lc <= 'm') ? 13
: ((lc >= 'n' && lc <= 'z') ? -13 : 0)
return c
}
}

rot47 := |Str s -> Str|
{
rot(s) |Int c -> Int|
{
c += (c >= '!' && c <= 'O') ? 47
: ((c >= 'P' && c <= '~') ? -47 : 0)
return c
}
}

s := "Hello World #123"
echo("s=$s")
echo("rot13=${rot13(s)}")
echo("rot47=${rot47(s)}")