View Category

Output a string to the console

Write the string "Hello World!" to STDOUT
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 "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?
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")

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.

Define a string containing special characters

Define the literal string "\#{'}${"}/"
fsharp
let special = "\#{'}${\"}/"

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
fsharp
let multiline = "This\nIs\nA\nMultiline\nString"
let multiline = "This
Is
A
Multiline
String"

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
fsharp
let a, b = 3, 4
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"
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 words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
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. " 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.
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 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

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
fsharp
let s = " hello "
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
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 |])

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
fsharp
printfn "%s" ("Space Monkey".ToUpper())
printfn "%s" (String.uppercase "Space Monkey")

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
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"
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))
// 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 culture = System.Globalization.CultureInfo.GetCultureInfo("en-US")
let titleCase = culture.TextInfo.ToTitleCase "man oF sTeel"