View Subcategory

Output a string to the console

Write the string "Hello World!" to STDOUT
ruby
puts "Hello World!"
$stdout<<"Hello World!"
java
System.out.println("Hello World!");
System.out.printf("Hello World!\n");
perl
print "Hello World!\n"
groovy
println "Hello World!"
scala
println("Hello World!")
printf("Hello World!\n")
python
print "Hello World!"
# python 3 requires parentheses for print

print('Hello, world!\n')
cpp
std::cout << "Hello World" << std::endl;
std::printf("Hello World\n");
Console::WriteLine(L"Hello World");
fsharp
printfn "Hello World!"
erlang
io:format("Hello, World!~n").
ocaml
print_string "Hello world!\n";;
print_endline "Hello world!";;
Printf.printf "Hello world!\n";;
csharp
System.Console.WriteLine("Hello World!")
php
echo 'Hello World!';
/****
* For some (security)reason I couldn't
* submit this without adding a space to
* the functionname. Please remove it :)
****/

// The correct way in command line-mode. :)
f write(STDOUT, "Hello World!\n");
haskell
main = putStrLn "Hello World!"
clojure
(println "Hello World!")
fantom
echo("Hello World!")
go
fmt.Printf("Hello, world\n")
fmt.Println("Hello, World!")

Retrieve a string containing ampersands from the variables in a url

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

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

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

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

Of course this fails for the same reasons. What is a better approach?
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"
url = "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith"
url = URI.parse(URI.encode(url))
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());
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}
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")
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)
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("&")
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'.
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();
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)
// 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")
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, "&"),...
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
php
/************************
* This is definitely not what this site is about
* This is not a site where you can get help with various problems
* It's a site where you can say:
* "How do you do the following in your language"
*
*************
*
* Anyway...
* I would use urlencode like you have tried
* (or to be on the safe side: rawurlencode() )
************************/

$parameter = "Bart & Lisa";
echo "<a href='".basename(__FILE__)."?fname=".$parameter."'>?fname=".$parameter."</a><br />\n";
echo "<a href='".basename(__FILE__)."?fname=".rawurlencode($parameter)."'>?fname=".rawurlencode($parameter)."</a><br />\n";

echo "<pre>", print_r($_REQUEST, true), "</pre>";

/***************
* Try to save this as a file and run the script
************
* If you hover the mouse over the link, they will look exactly the same
* but if you click them, they will output differently
***************/


// Cheers, "Josso"

echo("The given input URL is mal-formed; it should be URL-encoded. Use urldecode() on each argument to decode it.");

$url = parse_url("http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith");
$query = $url['query'];
$query = preg_replace("/&(?=[^=]*&)/", "%26", $query);
parse_str($query, $querystring);
var_dump($querystring);

the result is >> array(3) {
["mode"]=>
string(4) "view"
["fname"]=>
string(10) "Ron & Jean"
["lname"]=>
string(5) "Smith"
}
haskell
import Network.CGI

query = "http://myserver.com/custinfo/edit.php?" ++ formEncode [("mode", "view"), ("fname", "Ron & Jan"), ("lname","Smith")]
clojure
(->> {"mode" "view"
"fname" "Ron & Jean"
"lname" "Smith"}
(map #(str (URLEncoder/encode (first %) "UTF-8")
"="
(URLEncoder/encode (second %) "UTF-8")))
(reduce (fn [url e] (str url "&" e))
"http://myserver.com/custinfo/edit.php"))
fantom
encoded := `http://myserver.com/custinfo/edit.php`.plusQuery(
["fname":"Ron & Jean", "lname":"Smith"]).encode
echo(encoded)

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "

Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
ruby
str = "The quick brown fox jumps over the lazy dog. " * 10
outarr = str.scan(/[^ ].{0,76}/)
outarr.each{ |line| puts "> %s" % line }
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 class PangramWrapper {
public static void main(String[] args) {
int lineLimit = 78;
String newLine = "\n> ";
String pangram = "The quick brown fox jumps over the lazy dog. ";
String repeated = new String(new char[10]).replace("\0", pangram);

StringBuffer all = new StringBuffer(newLine + repeated);
for(int count = 1; count*lineLimit < all.length(); count++) {
all.insert(count * lineLimit, newLine);
}
System.out.println(all);
}
}
public class PangramWrapperViaRegexAndJoin {
public static void main(String[] args) {
String newLine = "\n> ",
pangram = "The quick brown fox jumps over the lazy dog. ",
repeated = new String(new char[10]).replace("\0", pangram);

final String[] splitted = repeated.split("(?<=\\G.{78})"); // worse performance than substring in for-loop
System.out.println("> "+ String.join(newLine, Arrays.asList(splitted)));
}
}
perl
print map"> $_\n",("The quick brown fox jumps over the lazy dog. " x 10)=~/(.{1,77}) ?/g;
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"
}
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 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))
("The quick brown fox jumps over the lazy dog. " * 10) grouped(78) foreach { line => println("> " + line) }
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)
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);
}
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]).
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 ()
php
foreach(str_split(str_repeat("The quick brown fox jumps over the lazy dog. ", 10), 77) as $line)
printf("> %s\n", trim($line));
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. "
tenTimes = concat . replicate 10 $ "The quick brown fox jumps over the lazy dog. "
warp n = takeWhile (/="") . unfoldr (Just . splitAt n)
main = mapM_ (putStrLn . ("> " ++)) $ warp 77 tenTimes
mapM_ (putStrLn . ("> " ++)) $ takeWhile (/="") . unfoldr (Just . splitAt 77) . concat . replicate 10 $ "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)))
(defn wrap
"the expected output shown wraps at 77, rather than 78"
[s]
(if (empty? s)
nil
(cons (apply str (take 77 s))
(wrap (drop 77 s)))))

(->> (repeat 10 "The quick brown fox jumps over the lazy dog. ")
(apply str)
(wrap)
(map #(println "> " %)))
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 : ""
}
go
package main

import (
"fmt"
"strings"
)

func main() {
str := "The quick brown fox jumps over the lazy dog. "
chs := strings.Split(str, "")
j := 1
for i := 0; i < 10; i++ {
for n, l := 0, len(chs); n < l; n++ {
if j == 1 {
fmt.Print("> ")
}
fmt.Print(chs[n])
if j == 77 {
fmt.Println()
j = 1;
}else {
j++;
}
}
}
}
package main

func main() {
chs := []rune("The quick brown fox jumps over the lazy dog. ")
j := 1
for i := 0; i < 10; i++ {
for _, v := range chs {
if j == 1 {
print("> ")
}
print(string(v))
if j == 77 {
println()
j = 1;
}else {
j++;
}
}
}
}