开发者

F#: Remove the first N characters from a string?

I'm trying to write some code to remove the first N characters in a string. I could have done this in an imperative manner already, but I would开发者_如何学编程 like to see it done in the spirit of functional programming. Being new to F# and functional programming, I'm having some trouble...


"Hello world".[n..];;


As @Jeff has shown, you can do this in six characters, so this is not necessarily the best question to ask to see how to "do it in the spirit of functional programming".

I show another way, which is not particularly "functional" (as it uses arrays, but at least it doesn't mutate any), but at least shows a set of steps.

let s = "Hello, world!"
// get array of chars
let a = s.ToCharArray()
// get sub array (start char 7, 5 long)
let a2 = Array.sub a 7 5
// make new string
let s2 = new string(a2)
printfn "-%s-" s2  // -world-


"Hello world".Substring 3


let rec remove_first_n (str:string) (n:int) =
  match str, n with
  | _, n when n <= 0 -> str
  | "", _ -> ""
  | _ -> remove_first_n (str.Remove(0,1)) (n-1)


Another way to do it (not particularly functional either). In fact it uses features of both world: mutation and lambda:

let remove_first_n (s:string) (n:int) =
    let arr = Array.create (s.Length-n) '0'
    String.iteri (fun i c -> if i>=n then arr.[i-n] <- c else ()) s
    new string(arr)

That being said, I think the best way is Jeff's solution.

One more thing to keep in mind is that Strings are immutable in .NET (a string value cannot be modified once built) and that F# strings are actually .NET Strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜