【F#2.0系列】介绍String类型


使用String

  几种不同的String书写方式:

  示例   种类   类型
  "Humpty Dumpty"   字符串   string
  "c:\Program Files"   字符串   string
  @"c:Program Files"   无转义(Verbatim) string   string
  "xyZy3d2"B   Literal byte array   byte []
  'c'   字符   char

  转义字符:

  字符   含义   ASCII/Unicode 值   示例
  n   换行   10   "n"
  r   回车   13   "r"
  t   Tab   9   "t"
  b   Backspace   8
  NNN   使用三位数字表示的字符   NNN   "32" (space)
  uNNNN   Unicode 字符   NNNN   "u00a9" (?)
  UNNNNNNNN   Long Unicode 字符   NNNN NNNN   "U00002260"(_)

  Byte array中的字符都是ASCII字符。非ASCII字符需要使用转义符。

  将一个字符串写为两行:

> let s = "All the kings horses
- and all the kings men";;
val s : string

  支持通过.[]来访问字符串的特定字符:

> let s = "Couldn't put Humpty";;
val s : string
 
> s.Length;;
val it : int = 19
 
> s.[13];;
val it : char = 'H'

  使用.[index..index]可以获取子字符串(substring):

> let s = "Couldn't put Humpty";;
val s : string
 
> s.[13..16];;
val it : string = "Hump"

  字符串是不可变的(immutable);就是说,一个字符串的值在其生成之后就不能被改变。例如:Substring方法并不会修改原字符串本身,而是返回了一个新的字符串。

  当你视图修改一个字符串的时候,你会得到一个error:

> let s = "Couldn't put Humpty";;
val s : string = "Couldn't put Humpty"
 
> s.[13] <- 'h';;
 
  s.[13] <- 'h';;
  ^^
stdin(75,0): error: FS0001: Type error in the use of the overloaded operator
'set_Item'. The type 'string' does not support any operators named 'set_Item'

  构造一个字符串

  最简单的方式就是使用+操作符:

> "Couldn't put Humpty" + " " + "together again";;
val it : string = "Couldn't put Humpty together again"

  我们依然可以使用System.Text.StringBuilder来构建:

> let buf = new System.Text.StringBuilder();;
val buf : System.Text.StringBuilder
 
> buf.Append("Humpty Dumpty");;
 
> buf.Append(" sat on the wall");;
 
> buf.ToString();;
val it : string = "Humpty Dumpty sat on the wall"

  同时,F#兼容OCaml的^操作符。(感觉上和+是一回事。)


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3