View Category
Output a string to the console
Write the string
"Hello World!" to STDOUT
clojure
(println "Hello World!")
cpp
std::cout << "Hello World" << std::endl;
std::printf("Hello World\n");
Console::WriteLine(L"Hello World");
csharp
System.Console.WriteLine("Hello World!")
erlang
io:format("Hello, World!~n").
fantom
echo("Hello World!")
fsharp
printfn "Hello World!"
groovy
println "Hello World!"
haskell
main = putStrLn "Hello World!"
java
System.out.println("Hello World!");
System.out.printf("Hello World!\n");
ocaml
print_string "Hello world!\n";;
print_endline "Hello world!";;
Printf.printf "Hello world!\n";;
perl
print "Hello World!\n"
python
print "Hello World!"
ruby
puts "Hello World!"
$stdout<<"Hello World!"
scala
println("Hello World!")
printf("Hello World!\n")
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?
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();
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, "&"),...
fantom
encoded := `http://myserver.com/custinfo/edit.php`.plusQuery(
["fname":"Ron & Jean", "lname":"Smith"]).encode
echo(encoded)
["fname":"Ron & Jean", "lname":"Smith"]).encode
echo(encoded)
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")
groovy
// Given the nature of the question text, I am assuming the question
// is how to produce a application/x-www-form-urlencoded compliant string
def basename = 'http://somedomain.com/somebase/'
def parameter = 'Bart & Lisa'
// equivalent to php
println basename + URLEncoder.encode(parameter)
// recommended approach is to specify encoding
println basename + URLEncoder.encode(parameter, "UTF-8")
// is how to produce a application/x-www-form-urlencoded compliant string
def basename = 'http://somedomain.com/somebase/'
def parameter = 'Bart & Lisa'
// equivalent to php
println basename + URLEncoder.encode(parameter)
// recommended approach is to specify encoding
println basename + URLEncoder.encode(parameter, "UTF-8")
haskell
import Network.CGI
query = "http://myserver.com/custinfo/edit.php?" ++ formEncode [("mode", "view"), ("fname", "Ron & Jan"), ("lname","Smith")]
query = "http://myserver.com/custinfo/edit.php?" ++ formEncode [("mode", "view"), ("fname", "Ron & Jan"), ("lname","Smith")]
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());
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());
ocaml
let query =
Netencoding.Url.mk_url_encoded_parameters [
"mode", "view";
"fname", "Ron & Jean";
"lname", "Smith";
]
let url =
"http://myserver.com/custinfo/edit.php?" ^ query
Netencoding.Url.mk_url_encoded_parameters [
"mode", "view";
"fname", "Ron & Jean";
"lname", "Smith";
]
let url =
"http://myserver.com/custinfo/edit.php?" ^ query
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}
."?fname=".urlenc('Ron & Jean')
."&lname=".urlenc('Smith');
sub urlenc{my($s)=@_;$s=~s/([^A-Za-z0-9])/sprintf("%%%02X",ord($1))/seg;$s}
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'.
# 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'.
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))
scala
import java.net.URLEncoder
val params = Map("mode"->"view", "fname"->"Ron & Jean", "lname"->"Smith")
var url = ""
for ((k, v) <- params) { url += URLEncoder.encode(k) + "=" + URLEncoder.encode(v) }
println(url)
val params = Map("mode"->"view", "fname"->"Ron & Jean", "lname"->"Smith")
var url = ""
for ((k, v) <- params) { url += URLEncoder.encode(k) + "=" + URLEncoder.encode(v) }
println(url)
import java.net.URLEncoder
val params = Map("mode"->"view", "fname"->"Ron & Jean", "lname"->"Smith")
(for ((k, v) <- params) yield URLEncoder.encode(k) + "=" + URLEncoder.encode(v) ).mkString("&")
val params = Map("mode"->"view", "fname"->"Ron & Jean", "lname"->"Smith")
(for ((k, v) <- params) yield URLEncoder.encode(k) + "=" + URLEncoder.encode(v) ).mkString("&")
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.
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);
}
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]).
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 : ""
}
while(s.size>0){
echo("> "+s[0..(77.min(s.size))-1])
s=(s.size>77)?s[77..-1].trim : ""
}
groovy
'The quick brown fox jumps over the lazy dog. '.multiply(10).split('(?<=\\G.{76})').each{println '> ' + it}
st = "The quick brown fox jumps over the lazy dog. " * 10
width = 76
while(st){
(first, st) = st.length() > width? [st[0..width], st[(width+1)..-1].trim()] : [st, null]
println "> $first"
}
width = 76
while(st){
(first, st) = st.length() > width? [st[0..width], st[(width+1)..-1].trim()] : [st, null]
println "> $first"
}
haskell
wrap str
| length str <= 77 = [str]
| otherwise = [take 77 str] ++ wrap (drop 77 str)
mapM_ putStrLn . map ("> " ++) . wrap . concat . replicate 10 $ "The quick brown fox jumps over the lazy dog. "
| length str <= 77 = [str]
| otherwise = [take 77 str] ++ wrap (drop 77 str)
mapM_ putStrLn . map ("> " ++) . wrap . concat . replicate 10 $ "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);
}
}
}
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);
}
}
}
ocaml
let wrapper margin =
let cur = ref 0 in
fun word ->
let len = String.length word in
let beginning_of_line () =
Printf.printf "> %s" word;
cur := len + 2 in
if !cur = 0 then
beginning_of_line ()
else begin
cur := !cur + 1 + len;
if !cur <= margin then
Printf.printf " %s" word
else begin
print_newline ();
beginning_of_line ()
end
end
let wrap_string wrapper s =
let len = String.length s in
let rec aux_out i =
if i < len then
match s.[i] with
| ' ' | '\t' | '\n' ->
aux_out (i+1)
| _ -> aux_in i (i+1)
and aux_in i0 i =
if i >= len then
wrapper (String.sub s i0 (len - i0))
else match s.[i] with
| ' ' | '\t' | '\n' ->
wrapper (String.sub s i0 (i - i0));
aux_out (i+1)
| _ ->
aux_in i0 (i+1) in
aux_out 0
let () =
let base_string = "The quick brown fox jumps over the lazy dog. " in
let w = wrapper 78 in
for i = 1 to 10 do
wrap_string w base_string
done;
print_newline ()
let cur = ref 0 in
fun word ->
let len = String.length word in
let beginning_of_line () =
Printf.printf "> %s" word;
cur := len + 2 in
if !cur = 0 then
beginning_of_line ()
else begin
cur := !cur + 1 + len;
if !cur <= margin then
Printf.printf " %s" word
else begin
print_newline ();
beginning_of_line ()
end
end
let wrap_string wrapper s =
let len = String.length s in
let rec aux_out i =
if i < len then
match s.[i] with
| ' ' | '\t' | '\n' ->
aux_out (i+1)
| _ -> aux_in i (i+1)
and aux_in i0 i =
if i >= len then
wrapper (String.sub s i0 (len - i0))
else match s.[i] with
| ' ' | '\t' | '\n' ->
wrapper (String.sub s i0 (i - i0));
aux_out (i+1)
| _ ->
aux_in i0 (i+1) in
aux_out 0
let () =
let base_string = "The quick brown fox jumps over the lazy dog. " in
let w = wrapper 78 in
for i = 1 to 10 do
wrap_string w base_string
done;
print_newline ()
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)
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)
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 }
scala
object Wrap {
def wordWrap(str: String, width: Int, lineStart: String, reps: Int) = {
var strRepeated = ""
for(i <- 0 until reps) strRepeated += str
while(strRepeated.length > width) {
println(lineStart + strRepeated.substring(0, (width-1)))
strRepeated = strRepeated.substring(width)
}
println(lineStart + strRepeated)
}
def main(args: Array[String]) = {
wordWrap("The quick brown fox jumps over the lazy dog. ", 78, "> ", 10)
}
}
def wordWrap(str: String, width: Int, lineStart: String, reps: Int) = {
var strRepeated = ""
for(i <- 0 until reps) strRepeated += str
while(strRepeated.length > width) {
println(lineStart + strRepeated.substring(0, (width-1)))
strRepeated = strRepeated.substring(width)
}
println(lineStart + strRepeated)
}
def main(args: Array[String]) = {
wordWrap("The quick brown fox jumps over the lazy dog. ", 78, "> ", 10)
}
}
def stringWrap(s: String): List[String] =
if (s.length == 0) Nil else s.take(78) :: stringWrap(s.drop(78))
stringWrap("The quick brown fox jumps over the lazy dog. " * 10).foreach(line => println("> " + line))
if (s.length == 0) Nil else s.take(78) :: stringWrap(s.drop(78))
stringWrap("The quick brown fox jumps over the lazy dog. " * 10).foreach(line => println("> " + line))
("The quick brown fox jumps over the lazy dog. " * 10) grouped(78) foreach { line => println("> " + line) }
Define a string containing special characters
Define the literal string
"\#{'}${"}/"
clojure
(def special "\\#{'}${\"}/")
cpp
std::string special = "\\#{'}${\"}/";
String^ special = L"\\#{'}${\"}/";
csharp
string verbatim = @"\#{'}${""""}/";
string cStyle = "\\#{'}${\"\"}/";
string cStyle = "\\#{'}${\"\"}/";
erlang
Special = "\\#{'}\${\"}/",
fantom
special := Str<|\#{'}${"}/|>
fsharp
let special = "\#{'}${\"}/"
groovy
special = "\\#{'}\${\"}/"
special = '\\#{\'}${"}/'
special = /\#{'}${'$'}{"}\//
haskell
putStrLn "\"\\#{'}${\"}/\""
let special = "\\#{'}${\"}/"
java
String special = "\\#{'}${\"}/";
ocaml
"\\#{'}${\"}/"
perl
$special = '\#{\'}${"}/';
$special = q(\#{'}${"}/);
python
# yes, Python has way too many forms of string literals :)
print "\\#{'}${\"}/"
print "\\#{'}${"'"'"}/"
print r"""\#{'}${"}/"""
print '\\#{\'}${"}/'
print '\\#{'"'"'}${"}/'
print r'''\#{'}${"}/'''
print "\\#{'}${\"}/"
print "\\#{'}${"'"'"}/"
print r"""\#{'}${"}/"""
print '\\#{\'}${"}/'
print '\\#{'"'"'}${"}/'
print r'''\#{'}${"}/'''
ruby
special = '\#{\'}${"}/'
scala
val special = "\\#{'}${\"}/"
val special2 = """\#{'}${"}/"""
val special2 = """\#{'}${"}/"""
Define a multiline string
Define the string:
"This
Is
A
Multiline
String"
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";
csharp
string output = "This\nIs\nA\nMultiline\nString";
string output = @"This
Is
A
Multiline
String";
Is
A
Multiline
String";
erlang
Text = "This\nIs\nA\nMultiline\nString",
fantom
s := "This
Is
A
Multiline
String"
Is
A
Multiline
String"
fsharp
let multiline = "This\nIs\nA\nMultiline\nString"
let multiline = "This
Is
A
Multiline
String"
Is
A
Multiline
String"
groovy
def text =
"""This
Is
A
Multiline
String"""
"""This
Is
A
Multiline
String"""
def text = "This\nIs\nA\nMultiline\nString"
haskell
s = "This \
\Is \
\A \
\Multiline \
\String"
\Is \
\A \
\Multiline \
\String"
java
String text = "This\nIs\nA\nMultiline\nString";
String text =
"This\n" +
"Is\n" +
"A\n" +
"Multiline\n" +
"String"
"This\n" +
"Is\n" +
"A\n" +
"Multiline\n" +
"String"
ocaml
"This\nIs\nA\nMultiline\nString"
"This
Is
A
Multiline
String"
Is
A
Multiline
String"
perl
$text = 'This
Is
A
Multiline
String';
Is
A
Multiline
String';
$text = <<EOF;
This
Is
A
Multiline
String
EOF
This
Is
A
Multiline
String
EOF
python
text = """This
Is
A
Multiline
String"""
Is
A
Multiline
String"""
# with proper indentation
text = (
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String"
)
text = (
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String"
)
ruby
text = <<"HERE"
This
Is
A
Multiline
String
HERE
This
Is
A
Multiline
String
HERE
text = "This\nIs\nA\nMultiline\nString"
scala
val text = """This
Is
A
Multiline
String"""
Is
A
Multiline
String"""
val text = "This\nIs\nA\nMultiline\nString"
Define a string containing variables and expressions
Given variables a=3 and b=4 output
"3+4=7"
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;
csharp
int a = 3;
int b = 4;
Console.WriteLine("{0}+{1}={2}", a,b,a+b);
int b = 4;
Console.WriteLine("{0}+{1}={2}", a,b,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)]).
fantom
echo("$a+$b=${a+b}")
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
groovy
println "$a+$b=${a+b}"
printf "%d+%d=%d\n", a, b, a + b
haskell
import Text.Printf
main = do
let a = 3
let b = 4
printf "%d+%d=%d" a b (a + b)
main = do
let a = 3
let b = 4
printf "%d+%d=%d" a b (a + b)
a = 3
b = 4
s = show a ++ "+" ++ show b ++ "=" ++ show (a + b)
main = putStrLn s
b = 4
s = show a ++ "+" ++ show b ++ "=" ++ show (a + b)
main = putStrLn s
java
System.out.println(a + "+" + b + "=" + (a+b));
System.out.printf("%d+%d=%d\n", a, b, a + b);
ocaml
Printf.printf "%d+%d=%d" a b (a+b);;
Printf.printf "%d+%d=%d" a b (a+b);;
perl
print "$a+$b=${\($a+$b)}\n";
sprintf("%d+%d=%d", $a, $b, $a + $b);
print $a, '+', $b, '=', $a + $b;
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())
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)
"%d+%d=%d" % (a, b, a+b)
ruby
puts "#{a}+#{b}=#{a+b}"
puts "#{a}+#{b}=%s" % (a + b)
scala
printf("%d+%d=%d\n", a, b, a + b)
"%d+%d=%d".format(a, b, a + b)
s"$a + $b = ${a+b}"
Reverse the characters in a string
Given the string
"reverse me", produce the string "em esrever"
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());
csharp
var str = "reverse me";
Console.WriteLine(new String(str.Reverse().ToArray()));
Console.WriteLine(new String(str.Reverse().ToArray()));
erlang
Reversed = lists:reverse("reverse me"),
Reversed = revchars("reverse me"),
fantom
"reverse me".reverse
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) []
groovy
reversed = "reverse me".reverse()
haskell
reverse "reverse me"
java
String reverse = new StringBuffer("reverse me").reverse().toString();
String reverse = new StringBuilder("reverse me").reverse().toString();
String reverse = StringUtils.reverse("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 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
;;
let l = Str.split (Str.regexp "") str in
List.fold_left (fun a b -> b ^ a) "" l
;;
perl
$_ = reverse "reverse me"; print
python
"reverse me"[::-1]
ruby
puts "reverse me".reverse
scala
val reversed = "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"
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();
csharp
var str = "This is a end, my only friend!";
str = String.Join(" ", str.Split().Reverse().ToArray());
Console.WriteLine(str);
str = String.Join(" ", str.Split().Reverse().ToArray());
Console.WriteLine(str);
erlang
Reversed = string:join(lists:reverse(string:tokens("This is the end, my only friend!", " ")), " "),
fantom
"This is a end, my only friend!".split.reverse.join(" ")
fsharp
let reversed = String.Join(" ", Array.rev("This is the end, my only friend!".Split [|' '|]))
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!")
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)
haskell
unwords (reverse (words "This is the end, my only friend!"))
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();
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();
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!", ' ');
ocaml
let rev_words str =
let l = Str.split (Str.regexp " ") str in
String.concat " " (List.rev l)
;;
let l = Str.split (Str.regexp " ") str in
String.concat " " (List.rev l)
;;
perl
$reversed = join ' ', reverse split / /, $text;
python
' '.join(reversed("This is a end, my only friend!".split()))
ruby
reversed = text.split.reverse.join(' ')
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(" ")
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.
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);
}
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));
}
}
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));
}
}
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")).
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++
}
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++
}
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
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, '> ')
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, '> ')
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 }
input = 'The quick brown fox jumps over the lazy dog. '
wrap(input * 10, 72 - prefix.size()).eachLine{ println prefix + it }
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))
-- 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))
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);
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);
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
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
perl
use Text::Wrap;
$text = "The quick brown fox jumps over the lazy dog. ";
$Text::Wrap::columns = 73;
print wrap('> ', '> ', $text x 10);
$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;
s/(.{0,70}) /> $1\n/g;
print;
python
import textwrap
print textwrap.fill("The quick brown fox jumps over the lazy dog. " * 10,
72, initial_indent="> ", subsequent_indent="> ")
print textwrap.fill("The quick brown fox jumps over the lazy dog. " * 10,
72, initial_indent="> ", subsequent_indent="> ")
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")
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)}
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(" "))
}
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(" "))
}
Remove leading and trailing whitespace from a string
Given the string
" hello " return the string "hello".
clojure
(use 'clojure.contrib.str-utils2)
(trim " hello ")
(trim " hello ")
(clojure.string/trim " hello ")
(.trim " hello ")
cpp
String^ s = " hello "; String^ trimmed = s->Trim();
csharp
string str = " hello ";
str = str.Trim();
Console.WriteLine(str);
str = str.Trim();
Console.WriteLine(str);
erlang
Trimmed = string:strip(S),
fantom
s := " hello ".trim
fsharp
let s = " hello "
let trimmed = s.Trim()
let trimmed = s.Trim()
let trimmed = " hello ".Trim()
groovy
assert "hello" == " hello ".trim()
haskell
unwords (words " hello ")
java
String s = " hello "; String trimmed = s.trim();
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
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
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;
$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}{};
$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
# 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
python
assert 'hello' == ' hello '.strip()
ruby
puts " hello ".strip
" hello ".strip!
scala
val 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
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
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;
}
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).
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)}")
{
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)}")
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 |])
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'
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'
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
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
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 ) )) ;
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 ) )) ;
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
| '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
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";
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";
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"])
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')
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")
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")
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")
Make a string uppercase
Transform
"Space Monkey" into "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);
csharp
string output = "Space Monkey"
System.Console.WriteLine(output.ToUpper())
System.Console.WriteLine(output.ToUpper())
erlang
io:format("~s~n", [string:to_upper("Space Monkey")]).
fantom
s := "Space Monkey".localeUpper
fsharp
printfn "%s" ("Space Monkey".ToUpper())
printfn "%s" (String.uppercase "Space Monkey")
groovy
println "Space Monkey".toUpperCase()
haskell
toUpperCase oldstring converted = if oldstring == ""
then converted
else toUpperCase (tail(oldstring)) (converted ++ [Char.toUpper(head(oldstring))])
toUpperCase "Space Monkey" ""
then converted
else toUpperCase (tail(oldstring)) (converted ++ [Char.toUpper(head(oldstring))])
toUpperCase "Space Monkey" ""
toUpperCase = map Char.toUpper
toUpperCase "Space Monkey"
toUpperCase "Space Monkey"
java
String upper = text.toUpperCase();
ocaml
String.uppercase "Space Monkey";;
perl
print uc "Space Monkey"
python
"Space Monkey".upper()
ruby
uppper = text.upcase
scala
println("Space Monkey".toUpperCase)
Make a string lowercase
Transform
"Caps ARE overRated" into "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();
csharp
string str = "Caps ARE overRated";
str = str.ToLower() ;
Console.WriteLine(str);
str = str.ToLower() ;
Console.WriteLine(str);
erlang
io:format("~s~n", [string:to_lower("Caps ARE overRated")]).
fantom
s := "Caps ARE overRated".localeLower
fsharp
printfn "%s" ("Caps ARE overRated".ToLower())
printfn "%s" (String.lowercase "Caps ARE overRated")
groovy
println "Caps ARE overRated".toLowerCase()
haskell
import Char
str = map toLower "Caps ARE overRated"
str = map toLower "Caps ARE overRated"
java
"Caps ARE overRated".toLowerCase();
ocaml
String.lowercase "Caps ARE overRated";;
perl
print lc "Caps ARE overRated"
python
"Caps ARE overRated".lower()
ruby
"Caps ARE overRated".downcase
scala
"Caps ARE overRated".toLowerCase
Capitalise the first letter of each word
Transform
"man OF stEEL" into "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();
csharp
System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase("man OF stEEL".ToLowerInvariant());
erlang
Caps = string:join(lists:map(fun(S) -> to_caps(S) end, string:tokens("man OF stEEL", " ")), " "),
fantom
"man OF stEEL".split.map { it.localeLower.localeCapitalize }.join(" ")
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"
groovy
def capitalize(s) { s[0].toUpperCase() + s[1..-1].toLowerCase() }
caps = "man OF stEEL".replaceAll(/\w+/) { w -> capitalize(w) }
caps = "man OF stEEL".replaceAll(/\w+/) { w -> capitalize(w) }
caps = "man OF stEEL".replaceAll(/\w+/) { w -> StringUtils.capitalize(w.toLowerCase()) }
caps = WordUtils.capitalizeFully("man OF stEEL")
haskell
import Data.Char
capitalizeWords = unwords . map capitalizeWord . words
where capitalizeWord [] = []
capitalizeWord (c:cs) = toUpper c : map toLower cs
capitalizeWords = unwords . map capitalizeWord . words
where capitalizeWord [] = []
capitalizeWord (c:cs) = toUpper c : map toLower cs
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();
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)));
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);
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");
ocaml
let capitalize_words str =
let len = String.length str in
let res = String.copy str in
let rec aux i do_up =
if i >= len then res else
match str.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (succ i) true
| _ ->
res.[i] <-
(if do_up then Char.uppercase else Char.lowercase) str.[i];
aux (succ i) false
in
aux 0 true
let () =
print_endline (capitalize_words "man OF stEEL")
let len = String.length str in
let res = String.copy str in
let rec aux i do_up =
if i >= len then res else
match str.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (succ i) true
| _ ->
res.[i] <-
(if do_up then Char.uppercase else Char.lowercase) str.[i];
aux (succ i) false
in
aux 0 true
let () =
print_endline (capitalize_words "man OF stEEL")
perl
$text =~ s/(\w+)/\u\L$1/g;
python
from string import capwords
capwords("man OF stEEL")
capwords("man OF stEEL")
' '.join(s.capitalize() for s in "man OF stEEL".split())
"man OF stEEL".title()
ruby
caps = text.gsub(/\w+/) { $&.capitalize }
caps = text.split.each{|i| i.capitalize!}.join(' ')
text.split.map(&:capitalize) * ' '
scala
def capitalize(s: String) = { s(0).toUpperCase + s.substring(1, s.length).toLowerCase }
"man OF stEEL".split("\\s") foreach {(x) => text.append(capitalize(x)).append(" ")}
"man OF stEEL".split("\\s") foreach {(x) => text.append(capitalize(x)).append(" ")}
val text = WordUtils.capitalizeFully("man OF stEEL")
val text = StringUtils.join("man OF stEEL".split("\\s") map {(x) => StringUtils.capitalize(x.toLowerCase) + " "})
// can be solved without external libraries
(("man OF stEEL" toLowerCase) split " " map (_ capitalize)).mkString(" ")
(("man OF stEEL" toLowerCase) split " " map (_ capitalize)).mkString(" ")
// This is just a slightly more compact form of the previous solution (my fav).
// It would be nice if split defaulted to whitespace (precompiled reg ex).
"man OF stEEL".toLowerCase.split(" ").map(_.capitalize) mkString " "
// It would be nice if split defaulted to whitespace (precompiled reg ex).
"man OF stEEL".toLowerCase.split(" ").map(_.capitalize) mkString " "
