Edit a string in OCAML Ask Question

I want to edit my string by using a function call edit which will produce a string in which each line (concluded by a \n character) is not longer than the base integer. Here are some illustrations:

edit p1 12 ;;

string = “Hello world!\nHow are you\ntoday? I\nhope all is\nwell.”

print_endline (edit p1 12) ;;
Hello world!
How are you
today? I
hope all is
well.

  • : unit = ()

edit p1 11 ;;

string = “Hello\nworld! How\nare you\ntoday? I\nhope all is\nwell.”

utop # print_endline (edit p1 11) ;;
Hello
world! How
are you
today? I
hope all is
well.

  • : unit = ()
    Since the length of “Hello world!” is 12, so it fits on a single line when 12 is the paragraph width, but it gets split when the paragraph width is set to 11. When the width is set to 4, which is less than the length of Hello, we don’t split the single word but still keep it in one line.

I am thinking of splitting the original string into a string list such as: [“Hello”;“world!”…] Then in my “edit” function, I want some conditions in it:

If the base integer is larger than the length of the string, then I just concatenate “Hello” ^ ’ ’ ^ “world” ^… Then I stop and check whether my new string is great than the base. I am stuck here. I don’t know how to move on. My method can be useless. This is all I can think of. Any input will be appreciated. Thank you!

If this is also coursework, I believe your tutor asks that you discuss with the rest of the class on the forum they keep linking to in this thread:
Achieving a desired number of elements out of a list OCAML

You’re on the right track though, check the documentation for the String module, and pay attention to the sub, concat, and length functions.

1 Like

Hi,
I have not got enough help because there are many people asking and there are not enough tutors. People try to play by rule but in fact, the benefits of students should be taken care of. I am posing questions on here to get guidance. Not to seek for direct solution.

Do you have any other thoughts on how to do this problem better?
Thanks!