2010-11-11 69 views
4

字符串我想从一个字符串更好的方式来获得的最后一个字符在F#

我有str.[str.Length - 1]的最后一个字符,但是这是丑陋的。一定会有更好的办法。

+0

这是为什么丑吗?你在找什么像str.LastChar()? – Prescott 2010-11-11 18:25:15

+0

我一直希望像'最后的' – 2010-11-11 18:27:01

+0

没有更好的办法(除非你自己写) – 2010-11-11 18:38:20

回答

11

有没有更好的方式来做到这一点 - 你有什么是好的。

如果你真的打算做了很多,你可以创作上的字符串类型的F#扩展属性:

let s = "food" 

type System.String with 
    member this.Last = 
     this.Chars(this.Length-1) // may raise an exception 

printfn "%c" s.Last 
0

你也可以把它当作一个序列,但我不知道这是任何或多或少比你有解决方案丑:

Seq.nth (Seq.length str - 1) str 
3

(这是一个老问题),有人可能会发现这个有用的原始答案从布赖恩。

type System.String with 

    member this.Last() = 
     if this.Length > 1 then 
      this.Chars(this.Length - 1).ToString() 
     else 
      this.[0].ToString() 
    member this.Last(n:int) = 
     let absn = Math.Abs(n) 
     if this.Length > absn then 
      let nn = 
       let a = if absn = 0 then 1 else absn 
       let b = this.Length - a 
       if b < 0 then 0 else b 
      this.Chars(nn).ToString() 
     else 
      this.[0].ToString() 

“ABCD”。去年() - > “d”

“ABCD”。去年(1) - > “d”

“ABCD”。去年( - 1) - > “d”

“ABCD”。去年(2) - > “C”

1

这可能是也很方便:

let s = "I am string" 
let lastChar = s |> Seq.last 

结果:

val lastChar : char = 'g' 
相关问题