View Category

Output a string to the console

Write the string "Hello World!" to STDOUT
perl
print "Hello World!\n"
java
System.out.println("Hello World!");
System.out.printf("Hello World!\n");
clojure
(println "Hello World!")
fantom
echo("Hello World!")

Retrieve a string containing ampersands from the variables in a url

My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as

"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".

The script variable for first name $_REQUEST['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.

I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)

Of course this fails for the same reasons. What is a better approach?
perl
print "http://myserver.com/custinfo/edit.php"
."?fname=".urlenc('Ron & Jean')
."&lname=".urlenc('Smith');
sub urlenc{my($s)=@_;$s=~s/([^A-Za-z0-9])/sprintf("%%%02X",ord($1))/seg;$s}
java
Map<String, String> params = new HashMap<String, String>();
params.put("mode", "view");
params.put("fname", "Ron & Jean");
params.put("lname", "Smith");

StringBuilder buffer = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
buffer.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
System.out.println(buffer.toString());
clojure
(->> {"mode" "view"
"fname" "Ron & Jean"
"lname" "Smith"}
(map #(str (URLEncoder/encode (first %) "UTF-8")
"="
(URLEncoder/encode (second %) "UTF-8")))
(reduce (fn [url e] (str url "&" e))
"http://myserver.com/custinfo/edit.php"))
fantom
encoded := `http://myserver.com/custinfo/edit.php`.plusQuery(
["fname":"Ron & Jean", "lname":"Smith"]).encode
echo(encoded)

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.
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);
}

}
}
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)))
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 : ""
}

Define a string containing special characters

Define the literal string "\#{'}${"}/"
perl
$special = '\#{\'}${"}/';
$special = q(\#{'}${"}/);
java
String special = "\\#{'}${\"}/";
clojure
(def special "\\#{'}${\"}/")
fantom
special := Str<|\#{'}${"}/|>

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
perl
$text = 'This
Is
A
Multiline
String';
$text = <<EOF;
This
Is
A
Multiline
String
EOF
java
String text = "This\nIs\nA\nMultiline\nString";
String text =
"This\n" +
"Is\n" +
"A\n" +
"Multiline\n" +
"String"
clojure
(def multiline "This\nIs\nA\nMultiline\nString")
fantom
s := "This
Is
A
Multiline
String"

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
perl
print "$a+$b=${\($a+$b)}\n";
sprintf("%d+%d=%d", $a, $b, $a + $b);
print $a, '+', $b, '=', $a + $b;
java
System.out.println(a + "+" + b + "=" + (a+b));
System.out.printf("%d+%d=%d\n", a, b, a + b);
clojure
(format "%d + %d = %d" a b (+ a b))
fantom
echo("$a+$b=${a+b}")

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
perl
$_ = reverse "reverse me"; print
java
String reverse = new StringBuffer("reverse me").reverse().toString();
String reverse = new StringBuilder("reverse me").reverse().toString();
String reverse = StringUtils.reverse("reverse me");
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/reverse "reverse me")
(apply str (reverse "reverse me"))
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"
perl
$reversed = join ' ', reverse split / /, $text;
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!", ' ');
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(" ")

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.
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;
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);
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++
}

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
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
java
String s = " hello "; String trimmed = s.trim();
clojure
(use 'clojure.contrib.str-utils2)
(trim " hello ")
(clojure.string/trim " hello ")
(.trim " 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
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";
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 ) )) ;
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)}")

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
perl
print uc "Space Monkey"
java
String upper = text.toUpperCase();
clojure
(.toUpperCase "Space Monkey")
fantom
s := "Space Monkey".localeUpper

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
perl
print lc "Caps ARE overRated"
java
"Caps ARE overRated".toLowerCase();
clojure
(.toLowerCase "Caps ARE overRated")
fantom
s := "Caps ARE overRated".localeLower

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
perl
$text =~ s/(\w+)/\u\L$1/g;
java
String input = "man OF stEEL";
StringTokenizer tokenizer = new StringTokenizer(input);
StringBuffer sb = new StringBuffer();
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
sb.append(word.substring(0, 1).toUpperCase());
sb.append(word.substring(1).toLowerCase());
sb.append(' ');
}
String text = sb.toString();
StringBuilder sb = new StringBuilder("man OF stEEL"); String s = sb.toString();
int last = s.length() - 1;

for (int i = 0; i <= last; ++i)
if (Character.isSpaceChar(s.charAt(i)) && i < last) { ++i; sb.setCharAt(i, Character.toUpperCase(s.charAt(i))); }
else if (i == 0) sb.setCharAt(i, Character.toUpperCase(s.charAt(i)));
else sb.setCharAt(i, Character.toLowerCase(s.charAt(i)));
Matcher m = Pattern.compile("(\\w+)").matcher("man OF stEEL"); StringBuffer sb = new StringBuffer(32), rsb = new StringBuffer(8);

while (m.find())
{
rsb.replace(0, rsb.length(), m.group().toLowerCase()); rsb.setCharAt(0, Character.toUpperCase(rsb.charAt(0)));
m.appendReplacement(sb, rsb.toString());
}
m.appendTail(sb);
String text = WordUtils.capitalizeFully("man OF stEEL");
clojure
(use 'clojure.contrib.str-utils2)
(join " " (map capitalize (split "man OF stEEL" #" ")))
fantom
"man OF stEEL".split.map { it.localeLower.localeCapitalize }.join(" ")