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

Go To


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.

2012-04-04 19:32
by EBM


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)
2012-04-04 19:52
by Thomas
You mean: if n > 0 && s.[n-1] = '\n' the - Martin Jambon 2012-04-04 20:25
I created a method that produced a very long string and I in some cases produced a "\n" in the end that I didn't want. Since I was near over schedule, I didn't have time to re-think it, so a fix like this seemed the solution xD. Thanks, you saved my project - EBM 2012-04-04 20:29
@MartinJambon is right, I forgot to handle the case where the size of n is 0. I've edited my answer accordingly - Thomas 2012-04-04 20:55