EBM
EBM

Reputation: 1099

Removing the eventual trailing '\n' in a string in OCaml

I need to create a function that receives a string and checks if the last char is a "\n" or not. If so, returns the same string without it's last char. The ways I can think of doing this are not the slightest efficient. I need it to be efficient.

Upvotes: 2

Views: 1847

Answers (1)

Thomas
Thomas

Reputation: 5048

It's hard to give a precise answer to your question as you do not give any context.

The simplest solution I can think of is:

let check s =
  let n = String.length s in
  if n > 0 && s.[n-1] = '\n' then
    String.sub s 0 (n-1)
  else
    s

Upvotes: 5

Related Questions