简单的字符串格式

有几种方法可以格式化并获取字符串作为结果。

.NET 的方式是使用 String.FormatStringBuilder.AppendFormat

open System
open System.Text

let hello = String.Format ("Hello {0}", "World")
// return a string with "Hello World"

let builder = StringBuilder()
let helloAgain = builder.AppendFormat ("Hello {0} again!", "World")
// return a StringBuilder with "Hello World again!"

F#还具有以 C 风格格式化字符串的功能。每个 .NET 函数都有等价物:

  • sprintf(String.Format):
open System

let hello = sprintf "Hello %s" "World" 
// "Hello World", "%s" is for string

let helloInt = sprintf "Hello %i" 42 
// "Hello 42", "%i" is for int

let helloFloat = sprintf "Hello %f" 4.2 
// "Hello 4.2000", "%f" is for float

let helloBool = sprintf "Hello %b" true 
// "Hello true", "%b" is for bool

let helloNativeType = sprintf "Hello %A again!" ("World", DateTime.Now) 
// "Hello {formatted date}", "%A" is for native type

let helloObject = sprintf "Hello %O again!" DateTime.Now 
// "Hello {formatted date}", "%O" is for calling ToString
  • bprintf(StringBuilder.AppendFormat):
open System
open System.Text

let builder = StringBuilder()

// Attach the StringBuilder to the format function with partial application
let append format = Printf.bprintf builder format

// Same behavior as sprintf but strings are appended to a StringBuilder
append "Hello %s again!\n" "World"
append "Hello %i again!\n" 42
append "Hello %f again!\n" 4.2
append "Hello %b again!\n" true
append "Hello %A again!\n" ("World", DateTime.Now)
append "Hello %O again!\n" DateTime.Now

builder.ToString() // Get the result string

使用这些函数而不是 .NET 函数提供了一些优点:

  • 类型安全
  • 部分申请
  • F#本机类型支持