📜  F#-字符串

📅  最后修改于: 2020-11-21 06:38:26             🧑  作者: Mango


在F#中,字符串类型将不可变文本表示为Unicode字符序列。

字符串字面量

字符串字面量用引号(“)字符分隔。

一些特殊字符用于特殊用途,例如换行符,制表符等。它们使用反斜杠(\)字符进行编码。反斜杠字符和相关字符构成转义序列。下表显示了F#支持的转义序列。

Character Escape sequence
Backspace \b
Newline \n
Carriage return \r
Tab \t
Backslash \\
Quotation mark \”
Apostrophe \’
Unicode character \uXXXX or \UXXXXXXXX (where X indicates a hexadecimal digit)

忽略转义序列的方法

以下两种方式使编译器忽略转义序列-

  • 使用@符号。
  • 用三引号将字符串来。

当字符串字面量以@符号开头时,称为逐字字符串。这样,将忽略字符串中的所有转义序列,除了将两个引号字符解释为一个引号字符。

当字符串用三引号引起来时,所有转义序列也将被忽略,包括双引号字符。

以下示例演示了此技术,该技术展示了如何使用XML或其他包含嵌入式引号的结构-

// Using a verbatim string
let xmldata = @""
printfn "%s" xmldata

编译并执行程序时,将产生以下输出-


字符串的基本运算符

下表显示了对字符串的基本操作-

Value Description
collect : (char → string) → string → string Creates a new string whose characters are the results of applying a specified function to each of the characters of the input string and concatenating the resulting strings.
concat : string → seq → string Returns a new string made by concatenating the given strings with a separator.
exists : (char → bool) → string → bool Tests if any character of the string satisfies the given predicate.
forall : (char → bool) → string → bool Tests if all characters in the string satisfy the given predicate.
init : int → (int → string) → string Creates a new string whose characters are the results of applying a specified function to each index and concatenating the resulting strings.
iter : (char → unit) → string → unit Applies a specified function to each character in the string.
iteri : (int → char → unit) → string → unit Applies a specified function to the index of each character in the string and the character itself.
length : string → int Returns the length of the string.
map : (char → char) → string → string Creates a new string whose characters are the results of applying a specified function to each of the characters of the input string.
mapi : (int → char → char) → string → string Creates a new string whose characters are the results of applying a specified function to each character and index of the input string.
replicate : int → string → string Returns a string by concatenating a specified number of instances of a string.

以下示例演示了上述某些功能的用法-

例子1

所述String.collect函数构建一个新的字符串,其字符是施加指定的函数到每个输入字符串的字符的并且链接该生成的字符串的结果。

let collectTesting inputS =
   String.collect (fun c -> sprintf "%c " c) inputS
printfn "%s" (collectTesting "Happy New Year!")

编译并执行程序时,将产生以下输出-

H a p p y N e w Y e a r !

例子2

String.concat函数将给定的字符串序列与分隔符连接起来,并返回一个新的字符串。

let strings = [ "Tutorials Point"; "Coding Ground"; "Absolute Classes" ]
let ourProducts = String.concat "\n" strings
printfn "%s" ourProducts

编译并执行程序时,将产生以下输出-

Tutorials Point
Coding Ground
Absolute Classes

例子3

该方法String.replicate通过级联字符串的实例中指定数量的返回一个字符串。

printfn "%s" 

编译并执行程序时,将产生以下输出-

*! *! *! *! *! *! *! *! *! *!