I don't know how to add some string to itself in loop.
let parameters = [| [| ("name", "fdjks"); ("value", "dsf") |]; [| ("name", "&^%"); ("value", "helo") |] |] ;;
let boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";;
let body = "";;
for x = 0 to (Array.length(parameters) : int)-1 do
let (_, paramName) = parameters.(x).(0) in
let (_, paramValue) = parameters.(x).(1) in
body = body ^ "--" ^ boundary ^ "\r\n" ^ "Content-Disposition:form-data; name=\"" ^ paramName ^ "\"\r\n\r\n" ^ paramValue ;
print_endline(body)
done;;
but this gives error.. Any way to do this......?
The (^)
operator concatenates two strings, e.g.,
# "hello" ^ ", " ^ "world!";;
- : string = "hello, world!"
If you have a list of strings, then you can use the String.concat
function, that takes a separator, and a list of strings and produces there concatentation in an effective way:
# String.concat ", " ["hello"; "world"];;
- : string = "hello, world"
Why is using the (^)
operator in a cycle is a bad idea? Every concatentation creates a new string and then copies the contents of both strings into the new string. So appending N
strings will end up in approximately n^2
copying (where n
is the length of a string). The same is true in Java and other languages/libraries where concatenation returns a new string, instead of mutating one of its arguments. A usual solution is to use the StringBuilder pattern, which in OCaml is represented with the Buffer module. So suppose, you don't have the String.concat
function, and you would like to build your own efficient concatenation function (this could also be useful, since Buffer
is a more general solution than String.concat
, and will work when, for example, you input is not a list). Here is our implementation,
let concat xs =
let buf = Buffer.create 16 in
List.iter (Buffer.add_string buf) xs;
Buffer.contents buf
This function will create a buffer that will automatically resize itself. The 16
is just an initial guess and could be any number. On the second line we just iterate over all strings and push the to the buffer, and finally, we ask the buffer to build the resulting string. Here is how we use this function:
# concat ["hello"; ", "; "world"];;
- : string = "hello, world"