String 在f中获取字符串中最后一个字符的更好方法#
我想要字符串中的最后一个字符String 在f中获取字符串中最后一个字符的更好方法#,string,f#,String,F#,我想要字符串中的最后一个字符 我有str.[str.Length-1],但那很难看。一定有更好的办法。没有比这更好的办法了——你所拥有的一切都很好 如果您真的打算经常这样做,您可以在字符串类型上编写一个F#扩展属性: let s = "food" type System.String with member this.Last = this.Chars(this.Length-1) // may raise an exception printfn "%c" s.L
我有
str.[str.Length-1]
,但那很难看。一定有更好的办法。没有比这更好的办法了——你所拥有的一切都很好
如果您真的打算经常这样做,您可以在字符串类型上编写一个F#扩展属性:
let s = "food"
type System.String with
member this.Last =
this.Chars(this.Length-1) // may raise an exception
printfn "%c" s.Last
您也可以将其视为一个序列,但我不确定这是否比您的解决方案更丑陋:
Seq.nth (Seq.length str - 1) str
(这是一个老问题),有人可能会从布赖恩那里找到这个有用的原始答案
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()
键入System.String和
成员:this.Last()=
如果此.Length>1,则
this.Chars(this.Length-1).ToString()
其他的
此[0].ToString()
成员这个。最后一个(n:int)=
设absn=Math.Abs(n)
如果此.Length>absn,则
设nn=
设a=如果absn=0,则1否则absn
设b=这个。长度-a
如果b<0,则其他b为0
this.Chars(nn).ToString()
其他的
此[0].ToString()
“ABCD”.Last()->“D” “ABCD”。最后一(1)->“D” “ABCD”。最后(-1)->“D”
“ABCD”。最后(2)->“C”这也很方便:
let s = "I am string"
let lastChar = s |> Seq.last
结果:
val lastChar : char = 'g'
为什么这么难看?你在寻找类似str.LastChar()的东西吗?我希望找到类似“str last”的东西没有更好的方法(除非你自己编写)与Python的相似之处让我想要类似于
str的东西。[-1:]
;然而,这样的语法会将Python的一个弱点引入C#:通过使它们变得漂亮来刺激计算代价高昂的操作。