我不知道如何在循环中向自身添加一些字符串。
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;;
Run Code Online (Sandbox Code Playgroud)
但这给出了错误..有什么方法可以做到这一点......?
该(^)运算符连接两个字符串,例如,
# "hello" ^ ", " ^ "world!";;
- : string = "hello, world!"
Run Code Online (Sandbox Code Playgroud)
如果您有一个字符串列表,那么您可以使用该String.concat函数,该函数接受分隔符和字符串列表,并以有效的方式生成连接:
# String.concat ", " ["hello"; "world"];;
- : string = "hello, world"
Run Code Online (Sandbox Code Playgroud)
(^)为什么在循环中使用运算符是一个坏主意?每次连接都会创建一个新字符串,然后将两个字符串的内容复制到新字符串中。因此,附加N字符串最终将近似复制n^2(其中n是字符串的长度)。在 Java 和其他语言/库中也是如此,其中连接返回一个新字符串,而不是改变其参数之一。通常的解决方案是使用StringBuilder 模式,它在 OCaml 中用Buffer模块表示。因此,假设您没有该String.concat函数,并且您想构建自己的高效串联函数(这也可能很有用,因为Buffer是一个比String.concat, 更通用的解决方案,并且在例如您输入不是列表)。这是我们的实现,
let concat xs =
let buf = Buffer.create 16 in
List.iter (Buffer.add_string buf) xs;
Buffer.contents buf
Run Code Online (Sandbox Code Playgroud)
该函数将创建一个缓冲区,该缓冲区会自动调整大小。这16只是初步猜测,可以是任何数字。在第二行,我们只是迭代所有字符串并将其推送到缓冲区,最后,我们要求缓冲区构建结果字符串。下面是我们如何使用这个函数:
# concat ["hello"; ", "; "world"];;
- : string = "hello, world"
Run Code Online (Sandbox Code Playgroud)