View Category

Output a string to the console

Write the string "Hello World!" to STDOUT
python
print "Hello World!"
erlang
io:format("Hello, World!~n").
clojure
(println "Hello World!")
cpp
std::cout << "Hello World" << std::endl;
std::printf("Hello World\n");
Console::WriteLine(L"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?
python
# I'm not really sure this is what the site is for,
# but the one unsolved problem for python was grating me.
# Anyway, I think this is what you're looking for.

from urllib import urlencode

query_dict = {'mode': 'view',
'fname': 'Ron & Jean',
'lname': 'Smith'}

print urlencode(query_dict.items())

# Which will be 'lname=Smith&mode=view&fname=Ron+%26+Jean'.
erlang
% encode ampersand in your string using %XX where XX is hex code for ampersand
% optionally encode spaces for completeness sake to keep URL solid
URL = "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron%20%26%20Jean&lname=Smith",
{_, Query} = string:tokens(URL, "?"),
KeyValuePairs = string:tokens(Query, "&"),...
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"))
cpp
QUrl url("http://myserver.com/custinfo/edit.php");
url.addQueryItem("mode", "view");
url.addQueryItem("fname", "Ron & Jean");
url.addQueryItem("lname", "Smith");
QByteArray encodedUrl = url.toEncoded();

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

Define a string containing special characters

Define the literal string "\#{'}${"}/"
python
# yes, Python has way too many forms of string literals :)
print "\\#{'}${\"}/"
print "\\#{'}${"'"'"}/"
print r"""\#{'}${"}/"""
print '\\#{\'}${"}/'
print '\\#{'"'"'}${"}/'
print r'''\#{'}${"}/'''
erlang
Special = "\\#{'}\${\"}/",
clojure
(def special "\\#{'}${\"}/")
cpp
std::string special = "\\#{'}${\"}/";
String^ special = L"\\#{'}${\"}/";

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
python
text = """This
Is
A
Multiline
String"""
# with proper indentation
text = (
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String"
)
erlang
Text = "This\nIs\nA\nMultiline\nString",
clojure
(def multiline "This\nIs\nA\nMultiline\nString")
cpp
std::string text =
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String";
String^ text = L"This\nIs\nA\nMultiline\nString";
std::string text = "This\nIs\nA\nMultiline\nString";

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
python
class EvalDict(dict):
def __getitem__(s, k):
return eval(k, s)

a=3; b=4
"%(a)d+%(b)d=%(a+b)d" % EvalDict(locals())
a=3; b=4
"%d+%d=%d" % (a, b, a+b)
erlang
A = 3, B = 4,
io:format("~B+~B=~B~n", [A, B, (A+B)]).
clojure
(format "%d + %d = %d" a b (+ a b))
cpp
Console::WriteLine(L"{0}+{1}={2}", a, b, a+b);
std::printf("%d+%d=%d\n", a, b, a+b);
std::cout << boost::format("%|1|+%|1|=%|1|") % a % b % (a+b) << std::endl;

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
python
"reverse me"[::-1]
erlang
Reversed = lists:reverse("reverse me"),
Reversed = revchars("reverse me"),
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/reverse "reverse me")
(apply str (reverse "reverse me"))
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());

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"
python
' '.join(reversed("This is a end, my only friend!".split()))
erlang
Reversed = string:join(lists:reverse(string:tokens("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!"))))
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();

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.
python
import textwrap
print textwrap.fill("The quick brown fox jumps over the lazy dog. " * 10,
72, initial_indent="> ", subsequent_indent="> ")
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")).
clojure
(doseq [line (re-seq #".{0,70} "
(apply str
(repeat 10 "The quick brown fox jumps over the lazy dog. ")))]
(println ">" line))
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);
}

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
python
assert 'hello' == ' hello '.strip()
erlang
Trimmed = string:strip(S),
clojure
(use 'clojure.contrib.str-utils2)
(trim " hello ")
(clojure.string/trim " hello ")
(.trim " hello ")
cpp
String^ s = " hello "; String^ trimmed = s->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
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')
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).
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))))
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;
}

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
python
"Space Monkey".upper()
erlang
io:format("~s~n", [string:to_upper("Space Monkey")]).
clojure
(.toUpperCase "Space Monkey")
cpp
String(L"Space Monkey").ToUpper();
std::string s = "Space Monkey";
std::transform(s.begin(), s.end(), s.begin(), std::toupper);
std::string s = "Space Monkey";
boost::to_upper(s);

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
python
"Caps ARE overRated".lower()
erlang
io:format("~s~n", [string:to_lower("Caps ARE overRated")]).
clojure
(.toLowerCase "Caps ARE overRated")
cpp
std::string s = "Caps ARE overRated";
std::string sl(boost::to_lower_copy(s));
String(L"Caps ARE overRated").ToLower();

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
python
from string import capwords
capwords("man OF stEEL")
' '.join(s.capitalize() for s in "man OF stEEL".split())
"man OF stEEL".title()
erlang
Caps = string:join(lists:map(fun(S) -> to_caps(S) end, string:tokens("man OF stEEL", " ")), " "),
clojure
(use 'clojure.contrib.str-utils2)
(join " " (map capitalize (split "man OF stEEL" #" ")))
cpp
std::string words = "mAn OF stEEL";
std::transform(words.begin(), words.end(), words.begin(), ToCaps<>());
StringBuilder^ sb = gcnew StringBuilder(L"man OF stEEL");

for (int i = 0, isFirst = 1; i < sb->Length; ++i)
{
sb[i] = Char::IsWhiteSpace(sb[i]) ? (isFirst = 1, sb[i]) : isFirst ? (isFirst = 0, Char::ToUpper(sb[i])) : Char::ToLower(sb[i]);
}
std::string words = "mAn OF stEEL";
std::vector<std::string> swv;

boost::split(swv, words, boost::is_any_of(" "));
std::string newwords = (std::for_each(swv.begin(), swv.end(), StringTAndJ(WordToCaps))).value();