How to resolve the algorithm Strip whitespace from a string/Top and tail step by step in the OCaml programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Strip whitespace from a string/Top and tail step by step in the OCaml programming language
Table of Contents
Problem Statement
Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results:
For the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Strip whitespace from a string/Top and tail step by step in the OCaml programming language
Source code in the ocaml programming language
let left_pos s len =
let rec aux i =
if i >= len then None
else match s.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (succ i)
| _ -> Some i
in
aux 0
let right_pos s len =
let rec aux i =
if i < 0 then None
else match s.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (pred i)
| _ -> Some i
in
aux (pred len)
let trim s =
let len = String.length s in
match left_pos s len, right_pos s len with
| Some i, Some j -> String.sub s i (j - i + 1)
| None, None -> ""
| _ -> assert false
let ltrim s =
let len = String.length s in
match left_pos s len with
| Some i -> String.sub s i (len - i)
| None -> ""
let rtrim s =
let len = String.length s in
match right_pos s len with
| Some i -> String.sub s 0 (i + 1)
| None -> ""
You may also check:How to resolve the algorithm Binary digits step by step in the Quackery programming language
You may also check:How to resolve the algorithm Command-line arguments step by step in the PL/I programming language
You may also check:How to resolve the algorithm Approximate equality step by step in the jq programming language
You may also check:How to resolve the algorithm Factorions step by step in the F# programming language
You may also check:How to resolve the algorithm Convert seconds to compound duration step by step in the JavaScript programming language