View Category
Output a string to the console
Write the string
"Hello World!" to STDOUT
ruby
puts "Hello World!"
$stdout<<"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");
fsharp
printfn "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
The script variable for first name $_REQUEST
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
Of course this fails for the same reasons. What is a better approach?
"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?
ruby
gem 'uri-query_params'
require 'uri/query_params'
url = URI("http://myserver.com/custinfo/edit.php?mode=view&fname=Ron%20&%20Jean&lname=Smith")
url.query_params['fname']
# => "Ron & Jean"
require 'uri/query_params'
url = URI("http://myserver.com/custinfo/edit.php?mode=view&fname=Ron%20&%20Jean&lname=Smith")
url.query_params['fname']
# => "Ron & Jean"
url = "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith"
url = URI.parse(URI.encode(url))
url = URI.parse(URI.encode(url))
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, "&"),...
% 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"))
"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();
url.addQueryItem("mode", "view");
url.addQueryItem("fname", "Ron & Jean");
url.addQueryItem("lname", "Smith");
QByteArray encodedUrl = url.toEncoded();
fsharp
//the problem arises due to the fact that you've attempted to apply HTML entities encoding rather than URL encoding to your data!
//in F#, for example, assuming you would call this function with fname and lname parameters, this would produce the desired output
let getProperUrl fname lname = sprintf "http://myserver.com/custinfo/edit.php?mode=view&fname=%s&lname=%s" (HttpUtility.UrlEncode fname) (HttpUtility.UrlEncode lname)
//in F#, for example, assuming you would call this function with fname and lname parameters, this would produce the desired output
let getProperUrl fname lname = sprintf "http://myserver.com/custinfo/edit.php?mode=view&fname=%s&lname=%s" (HttpUtility.UrlEncode fname) (HttpUtility.UrlEncode lname)
// Example that shows encoding and decoding:
let queryString =
let fname = HttpUtility.UrlEncode("Ron & James")
let lname = HttpUtility.UrlEncode("Smith & Jones")
sprintf "http://myserver.com/custinfo/edit.php?mode=view&fname=%s&lname=%s" fname lname
/// All parameters in the URL as a lookup map
let parameters =
let paramStart = queryString.IndexOf('?')
if paramStart < 0 then
Map.empty
else
let values =
queryString.Substring(paramStart + 1)
|> HttpUtility.ParseQueryString
values.AllKeys
|> Seq.map (fun key -> key, values.[key])
|> Map.ofSeq
let fname = parameters.TryFind("fname")
let lname = parameters.TryFind("lname")
let queryString =
let fname = HttpUtility.UrlEncode("Ron & James")
let lname = HttpUtility.UrlEncode("Smith & Jones")
sprintf "http://myserver.com/custinfo/edit.php?mode=view&fname=%s&lname=%s" fname lname
/// All parameters in the URL as a lookup map
let parameters =
let paramStart = queryString.IndexOf('?')
if paramStart < 0 then
Map.empty
else
let values =
queryString.Substring(paramStart + 1)
|> HttpUtility.ParseQueryString
values.AllKeys
|> Seq.map (fun key -> key, values.[key])
|> Map.ofSeq
let fname = parameters.TryFind("fname")
let lname = parameters.TryFind("lname")
string-wrap
Wrap the string
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.
"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.
ruby
str = "The quick brown fox jumps over the lazy dog. " * 10
outarr = str.scan(/[^ ].{0,76}/)
outarr.each{ |line| puts "> %s" % line }
outarr = str.scan(/[^ ].{0,76}/)
outarr.each{ |line| puts "> %s" % line }
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]).
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)))
(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);
}
#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
"\#{'}${"}/"
ruby
special = '\#{\'}${"}/'
erlang
Special = "\\#{'}\${\"}/",
clojure
(def special "\\#{'}${\"}/")
cpp
std::string special = "\\#{'}${\"}/";
String^ special = L"\\#{'}${\"}/";
fsharp
let special = "\#{'}${\"}/"
Define a multiline string
Define the string:
"This
Is
A
Multiline
String"
ruby
text = <<"HERE"
This
Is
A
Multiline
String
HERE
This
Is
A
Multiline
String
HERE
text = "This\nIs\nA\nMultiline\nString"
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";
"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";
fsharp
let multiline = "This\nIs\nA\nMultiline\nString"
let multiline = "This
Is
A
Multiline
String"
Is
A
Multiline
String"
Define a string containing variables and expressions
Given variables a=3 and b=4 output
"3+4=7"
ruby
puts "#{a}+#{b}=#{a+b}"
puts "#{a}+#{b}=%s" % (a + b)
erlang
A = 3, B = 4,
io:format("~B+~B=~B~n", [A, B, (A+B)]).
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;
fsharp
let a, b = 3, 4
let mystr = sprintf "%d+%d=%d" a b (a+b)
printfn "%s" mystr
let mystr = sprintf "%d+%d=%d" a b (a+b)
printfn "%s" mystr
Reverse the characters in a string
Given the string
"reverse me", produce the string "em esrever"
ruby
puts "reverse me".reverse
erlang
Reversed = lists:reverse("reverse me"),
Reversed = revchars("reverse me"),
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/reverse "reverse me")
(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);
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::reverse(s.begin(), s.end());
std::string s = "reverse me";
std::string sr(s.rbegin(), s.rend());
std::string sr(s.rbegin(), s.rend());
std::string s = "reverse me";
std::swap_ranges(s.begin(), (s.begin() + s.size() / 2), s.rbegin());
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) []
//reverse the word
let reversedword =
word.ToCharArray()
|> Array.fold(fun acc x -> x::acc) []
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(' ')
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!" #" ")))
(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);
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();
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 [|' '|]))
Text wrapping
Wrap the string
> 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.
"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")
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")
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")).
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))
(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);
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);
}
{
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 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
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
Remove leading and trailing whitespace from a string
Given the string
" hello " return the string "hello".
ruby
puts " hello ".strip
" hello ".strip!
erlang
Trimmed = string:strip(S),
clojure
(use 'clojure.contrib.str-utils2)
(trim " hello ")
(trim " hello ")
(clojure.string/trim " hello ")
(.trim " hello ")
cpp
String^ s = " hello "; String^ trimmed = s->Trim();
fsharp
let s = " hello "
let trimmed = s.Trim()
let trimmed = s.Trim()
let trimmed = " 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
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")
rot47 = "Hello World #123".tr!("\x21-\x7e", "\x50-\x7e\x21-\x4f")
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).
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))))
(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;
}
#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 |])
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 |])
Make a string uppercase
Transform
"Space Monkey" into "SPACE MONKEY"
ruby
uppper = text.upcase
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::transform(s.begin(), s.end(), s.begin(), std::toupper);
std::string s = "Space Monkey";
boost::to_upper(s);
boost::to_upper(s);
fsharp
printfn "%s" ("Space Monkey".ToUpper())
printfn "%s" (String.uppercase "Space Monkey")
Make a string lowercase
Transform
"Caps ARE overRated" into "caps are overrated"
ruby
"Caps ARE overRated".downcase
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));
std::string sl(boost::to_lower_copy(s));
String(L"Caps ARE overRated").ToLower();
fsharp
printfn "%s" ("Caps ARE overRated".ToLower())
printfn "%s" (String.lowercase "Caps ARE overRated")
Capitalise the first letter of each word
Transform
"man OF stEEL" into "Man Of Steel"
ruby
caps = text.gsub(/\w+/) { $&.capitalize }
caps = text.split.each{|i| i.capitalize!}.join(' ')
text.split.map(&:capitalize) * ' '
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" #" ")))
(join " " (map capitalize (split "man OF stEEL" #" ")))
cpp
std::string words = "mAn OF stEEL";
std::transform(words.begin(), words.end(), words.begin(), ToCaps<>());
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]);
}
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();
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();
fsharp
let words = String.Join(" ", Array.map (fun (s : String) -> (String.capitalize (s.ToLower()))) ("man OF stEEL".Split [|' '|]))
let wordlst = List.map (fun s -> (String.capitalize (String.lowercase s))) (String.split [' '] "man OF stEEL")
let words = new StringBuilder(List.hd wordlst)
for (s : String) in (List.tl wordlst) do (words.Append(" ").Append(s))
let words = new StringBuilder(List.hd wordlst)
for (s : String) in (List.tl wordlst) do (words.Append(" ").Append(s))
// Previous solutions used old library functions, here's something that works with F# 2.0
let s= "man OF stEEL"
let UpperFirst = function | "" -> "" | s -> s.Substring(0,1).ToUpper() + s.Substring(1).ToLower()
s.Split(' ') |> Array.map UpperFirst |> String.concat " "
let s= "man OF stEEL"
let UpperFirst = function | "" -> "" | s -> s.Substring(0,1).ToUpper() + s.Substring(1).ToLower()
s.Split(' ') |> Array.map UpperFirst |> String.concat " "
let culture = System.Globalization.CultureInfo.GetCultureInfo("en-US")
let titleCase = culture.TextInfo.ToTitleCase "man oF sTeel"
let titleCase = culture.TextInfo.ToTitleCase "man oF sTeel"
