Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

better way to get the last character in a string in f#

Tags:

string

f#

I want the last character from a string

I've got str.[str.Length - 1], but that's ugly. There must be a better way.

like image 872
Jonny Cundall Avatar asked Nov 11 '10 18:11

Jonny Cundall


People also ask

How do you get the last character of a string?

The strrchr() function returns a pointer to the last occurrence of c in string . If the given character is not found, a NULL pointer is returned. This example compares the use of strchr() and strrchr() .

How do I get the last 3 characters of a string?

string str = "AM0122200204"; string substr = str. Substring(str. Length - 3);


3 Answers

There's no better way to do it - what you have is fine.

If you really plan to do it a lot, you can author an F# extension property on the string type:

let s = "food"

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

printfn "%c" s.Last 
like image 141
Brian Avatar answered Nov 15 '22 09:11

Brian


This could be also handy:

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

Result:

val lastChar : char = 'g'
like image 33
Alamakanambra Avatar answered Nov 15 '22 07:11

Alamakanambra


(This is old question), someone might find this useful, orig answer from Brian.

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".Last() -> "D"

"ABCD".Last(1) -> "D"

"ABCD".Last(-1) -> "D"

"ABCD".Last(2) -> "C"

like image 37
Rommel Avatar answered Nov 15 '22 09:11

Rommel