View Subcategory

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
ruby
puts "reverse me".reverse
java
String reverse = new StringBuffer("reverse me").reverse().toString();
String reverse = new StringBuilder("reverse me").reverse().toString();
String reverse = StringUtils.reverse("reverse me");
perl
$_ = reverse "reverse me"; print
groovy
reversed = "reverse me".reverse()
scala
val reversed = "reverse me".reverse
python
"reverse me"[::-1]
cpp
String^ s = "reverse me";
array<Char>^ sa = s->ToCharArray();
Array::Reverse(sa);
String^ sr = gcnew String(sa);
std::string s = "reverse me";
std::reverse(s.begin(), s.end());
std::string s = "reverse me";
std::string sr(s.rbegin(), s.rend());
std::string s = "reverse me";
std::swap_ranges(s.begin(), (s.begin() + s.size() / 2), s.rbegin());
fsharp
let reversed = new String (Array.rev ("reverse me".ToCharArray()))
let word = "reverse me"
//reverse the word
let reversedword =
word.ToCharArray()
|> Array.fold(fun acc x -> x::acc) []
erlang
Reversed = lists:reverse("reverse me"),
Reversed = revchars("reverse me"),
ocaml
let reverse str =
let len = String.length str in
let res = String.create len in
for i = 0 to pred len do
let j = pred len - i in
res.[i] <- str.[j]
done;
(res)
let rev_char str =
let l = Str.split (Str.regexp "") str in
List.fold_left (fun a b -> b ^ a) "" l
;;
csharp
var str = "reverse me";
Console.WriteLine(new String(str.Reverse().ToArray()));
php
$reversed = strrev("reverse me");
haskell
reverse "reverse me"
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/reverse "reverse me")
(apply str (reverse "reverse me"))
fantom
"reverse me".reverse
go
package main;
import "utf8";
import "fmt";

func reverse(s string) string {
o := make([]int, utf8.RuneCountInString(s))
i := len(o)
for _, c := range s {
i--
o[i] = c
}
return string(o)
}

func main() {
fmt.Print(reverse("reverse me"));
}
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}

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"
ruby
reversed = text.split.reverse.join(' ')
java
List list = new ArrayList();
StringTokenizer st = new StringTokenizer(text, " ");
while(st.hasMoreTokens()) {
list.add(0, st.nextToken());
}
StringBuffer sb = new StringBuffer();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
String word = (String) iterator.next();
sb.append(word);
if (iterator.hasNext()) {
sb.append(" ");
}
}
String reversed = sb.toString();
List<String> ls = Arrays.asList("This is the end, my only friend!".split("\\s"));
Collections.reverse(ls);
StringBuilder sb = new StringBuilder(32); for (String s : ls) sb.append(" ").append(s);
String reversed = sb.toString().trim();
String reversed = StringUtils.reverseDelimited("This is the end, my only friend!", ' ');
perl
$reversed = join ' ', reverse split / /, $text;
groovy
reversed = "This is the end, my only friend!".split().reverse().join(' ')
reversed = "This is the end, my only friend!".tokenize(' ').reverse().join(' ')
def revdelim(c, s) { StringUtils.reverseDelimited(s, c) }
revwords = this.&revdelim.curry(" " as char)
reversed = revwords("This is the end, my only friend!")
reversed = StringUtils.reverseDelimited("This is the end, my only friend!", " " as char)
scala
"This is the end, my only friend!".split(" ").reverse.reduceLeft( (x,y) => x+' '+y )
val reversed = revwords("This is the end, my only friend!")
(("This is the end, my only friend!" split " ") reverse) mkString " "
val reversedText = text.split(" ").reverse.mkString(" ")
python
' '.join(reversed("This is a end, my only friend!".split()))
cpp
array<Char>^ sep = {L' '};
array<String^>^ words =
String(L"This is the end, my only friend!").Split(sep, StringSplitOptions::RemoveEmptyEntries);

Array::Reverse(words); String^ newwords = String::Join(L" ", words);
std::string words = "This is the end, my only friend!"; std::vector<std::string> swv;

boost::split(swv, words, boost::is_any_of(" ")); std::reverse(swv.begin(), swv.end());
std::string newwords = (std::for_each(swv.begin(), swv.end(), StringTAndJ())).value();
fsharp
let reversed = String.Join(" ", Array.rev("This is the end, my only friend!".Split [|' '|]))
erlang
Reversed = string:join(lists:reverse(string:tokens("This is the end, my only friend!", " ")), " "),
ocaml
let rev_words str =
let l = Str.split (Str.regexp " ") str in
String.concat " " (List.rev l)
;;
csharp
var str = "This is a end, my only friend!";
str = String.Join(" ", str.Split().Reverse().ToArray());
Console.WriteLine(str);
php
$reversed_words = implode(" ", array_reverse(explode(" ", "This is the end, my only friend!")));
haskell
unwords (reverse (words "This is the end, my only friend!"))
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/join " " (reverse (str/split "this is the end, my only friend!" #" ")))
(apply str (interpose " " (reverse (re-seq #"[^\s]+" "This is the end, my only friend!"))))
fantom
"This is a end, my only friend!".split.reverse.join(" ")
go
words := strings.Split("This is the end, my only friend!", " ")
nr := len(words)
reversed := make([]string, nr)
for i, word := range words {
reversed[nr - i - 1] = word
}
s := strings.Join(reversed, " ")
fmt.Println(s)
func reverse(list []string) ([]string) {
if len(list) == 1 {
return list
}

return append(reverse(list[1:]), list[0])
}

func main() {
words := strings.Split("This is the end, my only friend!", " ")
s := strings.Join(reverse(words), " ")
fmt.Println(s)
}

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.
ruby
prefix = "> "
string = "The quick brown fox jumps over the lazy dog. " * 10
width = 78
realwidth = width - prefix.length
print string.gsub(/(.{1,#{realwidth}})(?: +|$)\n?|(.{#{realwidth}})/, "#{prefix}\\1\\2\n")
# the same output is achieved with:
puts ("The quick brown fox jumps over the lazy dog. " * 10).gsub(/(.{1,70})(\s+|\Z)/, "> \\1\n")
# however
# "> The quick brown fox jumps over the lazy dog. The quick brown fox jumps".size => 72
# "> over the lazy dog. The quick brown fox jumps over the lazy dog. The".size + "quick".size # first line + first word of second line => 74
# where does 78 come from?
java
String prefix = "> "; String input = "The quick brown fox jumps over the lazy dog.";

String[] lines = WordUtils.wrap(StringUtils.repeat(input, 10), 72 - prefix.length()).split("\n");

for (String line : lines) System.out.printf("%s%s\n", prefix, line);
perl
use Text::Wrap;
$text = "The quick brown fox jumps over the lazy dog. ";
$Text::Wrap::columns = 73;
print wrap('> ', '> ', $text x 10);
$_ = "The quick brown fox jumps over the lazy dog. " x 10;
s/(.{0,70}) /> $1\n/g;
print;
groovy
// no built-in fill, define one using brute force approach
def fill(text, width=80, prefix='') {
width = width - prefix.size()
def out = []
List words = text.replaceAll("\n", " ").split(" ")
while (words) {
def line = ''
while (words) {
if (line.size() + words[0].size() + 1 > width) break
if (line) line += ' '
line += words[0]
words = words.tail()
}
out += prefix + line
}
out.join("\n")
}
println fill('The quick brown fox jumps over the lazy dog. ' * 10, 72, '> ')
// no built-in fill, define one using lastIndexOf
def fill(text, width=80, prefix='') {
def out = ''
def remaining = text.replaceAll("\n", " ")
while (remaining) {
def next = prefix + remaining
def found = next.lastIndexOf(' ', width)
if (found == -1) remaining = ''
else {
remaining = next.substring(found + 1)
next = next[0..found]
}
out += next + '\n'
}
out
}
println fill('The quick brown fox jumps over the lazy dog. ' * 10, 72, '> ')
prefix = '> '
input = 'The quick brown fox jumps over the lazy dog. '
wrap(input * 10, 72 - prefix.size()).eachLine{ println prefix + it }
scala
val prefix = "> " ; val input = "The quick brown fox jumps over the lazy dog."

WordUtils.wrap(input * 10, 72 - prefix.length).split("\n") foreach {(x) => printf("%s%s\n", prefix, x)}
def wrap(words: List[String]): List[List[String]] = words match {
case Nil => Nil
case _ =>
val output = (words.inits.dropWhile { _.mkString(" ").length > 78 }) next;
output :: wrap(words.drop(output.length))
}

wrap(("The quick brown fox jumps over the lazy dog. " * 10) split(" ") toList) foreach {
words => println("> " + words.mkString(" "))
}
python
import textwrap
print textwrap.fill("The quick brown fox jumps over the lazy dog. " * 10,
72, initial_indent="> ", subsequent_indent="> ")
cpp
String^ input = ::copies("The quick brown fox jumps over the lazy dog. ", 10);
String^ sep = " "; String^ prefix = "> ";

String^ wrapped = textwrap(input, 74 - prefix->Length, sep, prefix);
Console::WriteLine("{0}", wrapped);
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)
{
int line_len = width;
bool first_word = true;

width -= prefix.size();
BOOST_FOREACH(string word, tokenizer<char_separator<char>>(str, char_separator<char>(" ")))
{
line_len += word.size();
if (line_len++ < width)
os << ' ';
else {
if (first_word)
first_word = false;
else
os << endl;
os << prefix;
line_len = word.size();
}
os << word;
}
os << endl;
}

int main()
{
stringstream input;

rep(input, "The quick brown fox jumps over the lazy dog. ", 10);
wrap(cout, input.str(), "> ", 72);
}
fsharp
let prefix = "> "
let input = "The quick brown fox jumps over the lazy dog. "

(String.split ['\n'] (textwrap (copies input 10) (73 - prefix.Length))) |> List.iter (fun line -> printfn "%s%s" prefix line)
let output maxWidth (s: string) =
let rec wrap = function
| lineSoFar, ([| |]: string array)-> printfn "%s" lineSoFar
| ">" as lineSoFar, (words: string array) ->
// Handle this case separately, thus we can also deal with
// cases where a word is longer then the max width
wrap (lineSoFar + " " + words.[0], Array.sub words 1 (words.Length - 1))
| lineSoFar, words when words.[0].Length + lineSoFar.Length >= maxWidth ->
printfn "%s" lineSoFar
wrap (">", words)
| lineSoFar, words ->
wrap(lineSoFar + " " + words.[0], Array.sub words 1 (words.Length - 1))
wrap (">", s.Split([| ' ' |]))

[| for i in 1 .. 10 do yield "The quick brown fox jumps over the lazy dog." |]
|> String.concat " "
|> output 78
erlang
TextWrap = textwrap(string:copies(Input, 10), 73 - length(Prefix)),
lists:foreach(fun (Line) -> io:format("~s~n", [string:concat(Prefix, Line)]) end, string:tokens(TextWrap, "\n")).
ocaml
(* ocamlbuild -no-hygiene textwrap.native && ./textwrap.native *)

let wrap s prefix width =
let width = width - (String.length prefix) in
let len = String.length s in
let rec loop start =
if start >= len then
[]
else
let stop = min (len - start) width in
let sub = String.sub s start stop in
(prefix ^ sub) :: loop (start+stop)
in
loop 0
in

let wrap_and_print s prefix width =
List.iter print_endline (wrap s prefix width)
in
let s = ref "" in
for i = 1 to 10 do
s := !s ^ "The quick brown fox jumps over the lazy dog. "
done;
wrap_and_print !s "> " 78


csharp
using System;
using System.Text;
using System.Linq; // used for Array.ToList() extension

public class TextWrapper {

/// <summary>
/// Wrap the given text to a given width.
/// </summary>
/// <param name="text">The text to be wrapped</param>
/// <param name="width">The maximum width of each line</param>
/// <param name="prefix">Begin each line with this prefix</param>
/// <returns>The wrapped text</returns>
public string Wrap(string text, int width, string prefix) {

var words = text.Split(' ').ToList();
var result = new StringBuilder(prefix);

width = width - prefix.Length;
prefix = "\n" + prefix;

int lineSize = 0;
foreach (var word in words) {
int wordLen = word.Length;

// Do we need to start a new line?
if ((lineSize + wordLen) > width) {
result.Remove(result.Length - 1, 1); // remove trailing space
lineSize = 0;
result.Append( prefix );
}

result.Append(word).Append(' ');
lineSize += wordLen + 1;
}

return result.ToString();
}

public static void Main() {
var prefix = "> ";
var sentence = "The quick brown fox jumps over the lazy dog. ";

var text = "";
for (int i = 0; i < 10; i++)
text += sentence;

// The description said lines of length 78, but
// the example was 72...
Console.WriteLine(new TextWrapper().Wrap(text, 72, prefix));
}
}
php
$s = str_repeat("The quick brown fox jumps over the lazy dog. ", 10);
$s = wordwrap($s, 76, "WRAP");
$s = explode("WRAP", $s);
foreach ($s as $part) {
$res .= "> " . $part . "\n";
}
echo $res;
echo '> '.wordwrap(str_repeat('The quick brown fox jumps over the lazy dog. ', 10), 70,"\n> ")."\n";
haskell
import Data.List (intercalate)

-- our list of words ["The", "quick", "brown", ...]
dogs = concat$ replicate 10$ words "The quick brown fox jumps over the lazy dog."

-- ["The", "The quick", "The quick brown", ...]
concats = scanl1 (\s v -> s ++ " " ++ v)

-- takes list of words, returns list of lines
wordwrap :: Int -> [String] -> [String]
wordwrap maxwidth [] = []
wordwrap maxwidth ws = sentence : (wordwrap maxwidth restwords)
where
zipped = zip (concats ws) ws
(sentences, rest) = span (\(s,w) -> (length s) <= maxwidth) zipped
sentence = last (map fst sentences)
restwords = map snd rest

main = putStrLn ("> " ++ intercalate "\n> " (wordwrap 76 dogs))
clojure
(doseq [line (re-seq #".{0,70} "
(apply str
(repeat 10 "The quick brown fox jumps over the lazy dog. ")))]
(println ">" line))
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++
}
go
import "fmt"
import "strings"

const WIDTH = 72

func main() {
s := "The quick brown fox jumps over the lazy dog."

words := strings.Split(s, " ")
tmp := words

for i, pos := 0, 0; i < 10; i++ {
for len(words) > 0 {
if pos == 0 {
fmt.Printf("> ")
}

if pos + len(words[0]) > WIDTH {
fmt.Printf("\n")
pos = 0
} else {
fmt.Printf("%s ", words[0])
pos += len(words[0]) + 1
words = words[1:]
}
}
words = tmp
}

fmt.Printf("\n")
}

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
ruby
puts " hello ".strip
" hello ".strip!
java
String s = " hello "; String trimmed = s.trim();
perl
my $string = " hello ";
$string =~ s{
\A\s* # Any number of spaces at the start of the string
(.+?) # Remember any number of characters until we reach
\s*\z # any number of spaces at the end of the string
}{
$1 # Leave the characters we remembered
}x;
my $string = " hello ";
$string =~ s{\A\s*}{};
$string =~ s{\s*\z}{};

#Modification History:
# 2009-MAR-17: GGARIEPY: [creation] (geoff.gariepy@gmail.com)

$string = " hello ";
$string =~ s/^\s+|\s+$//g; # All the action happens in one regex!

# Regex Notes:
# ^ - anchors to the beginning of the string
# $ - anchors to the end of the string
# g - causes regex to match as many times as possible
# | - logical OR
groovy
assert "hello" == " hello ".trim()
scala
val s = " hello ".trim
python
assert 'hello' == ' hello '.strip()
cpp
String^ s = " hello "; String^ trimmed = s->Trim();
fsharp
let s = " hello "
let trimmed = s.Trim()
let trimmed = " hello ".Trim()
erlang
Trimmed = string:strip(S),
ocaml
let left_pos s len =
let rec aux i =
if i >= len then None
else match s.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (succ i)
| _ -> Some i
in
aux 0

let right_pos s len =
let rec aux i =
if i < 0 then None
else match s.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (pred i)
| _ -> Some i
in
aux (pred len)

let trim s =
let len = String.length s in
match left_pos s len, right_pos s len with
| Some i, Some j -> String.sub s i (j - i + 1)
| None, None -> ""
| _ -> assert false

let () =
let res = trim " hello " in
print_endline res
String.trim " hello "
csharp
string str = " hello ";
str = str.Trim();
Console.WriteLine(str);
php
$hello_trimmed = trim(" hello ");
haskell
unwords (words " hello ")
clojure
(use 'clojure.contrib.str-utils2)
(trim " hello ")
(clojure.string/trim " hello ")
(.trim " hello ")
fantom
s := " hello ".trim
go
s := strings.TrimSpace(" hello ")

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
ruby
rot13 = "Hello World #123".tr!("A-Za-z", "N-ZA-Mn-za-m")
rot47 = "Hello World #123".tr!("\x21-\x7e", "\x50-\x7e\x21-\x4f")
java
CharArrayWriter rot13 = new CharArrayWriter() ;
for (char c : i ) {
char lc = Character.toLowerCase(c) ;
rot13.append( c += ( (lc >= 'a' && lc <= 'm') ? 13 : ( (lc >= 'n' && lc <= 'z') ? -13 : 0 ) )) ;
}

CharArrayWriter rot47 = new CharArrayWriter() ;
for (char c : i )
rot47.append( c += ( (c >= '!' && c <= 'O') ? 47 : ( (c >= 'P' && c <= '~') ? -47 : 0 ) )) ;
perl
sub rot13 {
my $str = shift;
$str =~ tr/A-Za-z/N-ZA-Mn-za-m/;
return $str;
}

sub rot47 {
my $str = shift;
$str =~ tr/!-~/P-~!-O/;
return $str;
}

my $string = 'Hello World #123';

print "$string\n";
print rot13($string)."\n";
print rot47($string)."\n";
groovy
char rot13(s) {
char c = s
switch(c) {
case 'A'..'M': case 'a'..'m': return c+13
case 'N'..'Z': case 'n'..'z': return c-13
default : return c
}
}
String.metaClass.rot13 = {
delegate.collect(this.&rot13).join()
}

from = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
to = 'PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO'
String.metaClass.rot47 = {
delegate.collect{ int found = from.indexOf(it); found < 0 ? it : to[found] }.join()
}

assert 'Hello World #123'.rot13() == 'Uryyb Jbeyq #123'
assert 'Hello World #123'.rot47() == 'w6==@ (@C=5 R`ab'
scala
val uppers = 'A' to 'Z'
val lowers = 'a' to 'z'

val alpha13 = (uppers ++ lowers).mkString
val beta13 = ((uppers drop 13) ++ (uppers take 13) ++ (lowers drop 13) ++ (lowers take 13)).mkString

val alpha47 = """!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
val beta47 = """PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO"""

// generic translation function
def rot (alpha: String, beta: String)(c: Char) = if (alpha contains c) beta(alpha indexOf c) else c

// specific translation functions curried with the respective alphabets
val rot13 = rot(alpha13, beta13) _
val rot47 = rot(alpha47, beta47) _

assert(("Hello World #123" map rot13).toString == "Uryyb Jbeyq #123")
assert(("Hello World #123" map rot47).toString == "w6==@ (@C=5 R`ab")
python
# rot13, readable
rot13_tbl = string.maketrans("ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
string.translate("Hello World #123", rot13_tbl)


#
# "a bad programmer can write bad code in any language"
#

# rot13, "clever"
string.translate("Hello World #123", string.maketrans(string.lowercase+string.uppercase, string.lowercase[13:]+string.lowercase[:13]+string.uppercase[13:]+string.uppercase[:13]))

# rot47, very "clever"
''.join([ord(c) in range(33,127) and chr(((ord(c)-33+47)%(127-33))+33) or c for c in "Hello World #123"])

"Hello World #123".encode('rot13')
cpp
#include <algorithm>
#include <iostream>
#include <cctype>
using namespace std;

int rot13(int c) {
if (!isalpha(c)) {
return c;
} else {
char start = islower(c) ? 'a' : 'A';
return ((c - start) + 13) % 26 + start;
}
}

int rot47(int c) {
if (c < 33 || c > 126) {
return c;
} else {
return ((c - 33) + 47) % 94 + 33;
}
}

int main(int argc, char **argv) {
for (int i = 0; i < argc; ++i) {
string original = argv[i];

string rot13enc = original;
transform(original.begin(), original.end(), rot13enc.begin(), rot13);

string rot47enc = original;
transform(original.begin(), original.end(), rot47enc.begin(), rot47);

cout << "original: " << original << endl
<< "rot 13: " << rot13enc << endl
<< "rot 47: " << rot47enc << endl;
}
return 0;
}
fsharp
#light

let rotChar (s:int) (l:int) (h:int) (c:char) =
let charCode = int c
let letterCount = h - l + 1
let newCharCode = (charCode - l + s) % letterCount + l
char newCharCode

let rot13 (text:string) =
let rotChar13 = function
| (c:char) when 'A' <= c && c <= 'Z' -> rotChar 13 (int 'A') (int 'Z') c
| c when 'a' <= c && c <= 'z' -> rotChar 13 (int 'a') (int 'z') c
| c -> c
new string([| for c in text -> rotChar13 c|])

let rot47 (text:string) =
let rotChar47 = function
| ' ' as c -> c
| c -> rotChar 47 (int '!') (int '~') c
new string([| for c in text -> rotChar47 c |])
erlang
rot13(Str) ->
lists:map(fun(A) ->
if
A >= $A, A =< $Z -> ((A - $A + 13) rem 26) + $A;
A >= $a, A =< $z -> ((A - $a + 13) rem 26) + $a;
true -> A
end
end, Str).

rot47(Str) ->
lists:map(fun(A) ->
if
A >= $!, A =< $~ ->
((A - $! + 47) rem 94) + $!;
true -> A
end
end, Str).
ocaml
let rot_char13 c = match c with
| 'A'..'M' | 'a'..'m' -> Char.chr ((Char.code c) + 13)
| 'N'..'Z' | 'n'..'z' -> Char.chr ((Char.code c) - 13)
| _ -> c

let rot_char47 c = match c with
| '!'..'N' -> Char.chr ((Char.code c) + 47)
| 'O'..'~' -> Char.chr ((Char.code c) - 47)
| _ -> c

let rot f str =
let len = String.length str in
let res = String.create len in
for i = 0 to pred len do
res.[i] <- f str.[i]
done;
(res)

let rot13 = rot rot_char13
let rot47 = rot rot_char47
php
function rot13($str) {
return strtr($str,
"NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm",
"ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz");
}

function str_rot47($str) {
return strtr($str,
'!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
'PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO');
}

echo str_rot13("Hello World #123"); // builtin version
echo str_rot47("Hello World #123"); // homemade version
echo rot13("Hello World #123"); // homemade version
haskell
import Char

ebg13 c | isAlpha c && toLower c <= 'm' = chr ((ord c) + 13)
| isAlpha c && toLower c > 'm' = chr ((ord c) - 13)
| otherwise = c
rot13 str = map ebg13 str

ebg47 c | c > ' ' && c <= 'N' = chr ((ord c) + 47)
| c > 'N' && c <= '~' = chr ((ord c) - 47)
| otherwise = c
rot47 str = map ebg47 str
clojure
(use 'clojure.contrib.cond)

(defn rot13 [s]
(reduce str
(map #(char (let [c (bit-and (int (char %)) 0xDF)]
(+ % (cond-let [i]
(and (>= c (int \A)) (<= c (int \M))) 13
(and (>= c (int \N)) (<= c (int \Z))) -13
true 0))))
(map #(int (char %)) s))))

(defn rot47 [s]
(reduce str
(map #(char (+ % (cond-let [i]
(and (>= % (int \!)) (<= % (int \O))) 47
(and (>= % (int \P)) (<= % (int \~))) -47
true 0)))
(map #(int (char %)) s))))
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)}")