• Re: Searching a character within a line

    From B. Pym@21:1/5 to Pierre R. Mai on Sun Jul 7 11:43:16 2024
    Pierre R. Mai wrote:

    (defun get-field-from-line (field line)
    "Returns a copy of the given field (0 based index) from the line.
    Fields are separated by '|'. If there are fewer fields in line than
    field, nil is returned."
    (loop for start = 0 then (1+ position)
    for position = (and start (position #\| line :start start))
    repeat field
    when (null position)
    do (return nil)
    finally
    (return (subseq line start position))))

    Gauche Scheme

    (use srfi-13) ;; string-take string-index

    (define (get-field-of-line index line)
    (let go ((i index) (s line))
    (let ((found (string-index s #\|)))
    (if (zero? i)
    (or (and found (string-take s found)) s)
    (and found (go (- i 1) (string-drop s (+ 1 found))))))))

    (get-field-of-line 0 "|2|Dollars|23-dec-1999|Idaho")
    ===>
    ""

    (get-field-of-line 1 "|2|Dollars|23-dec-1999|Idaho")
    ===>
    "2"

    (get-field-of-line 2 "|2|Dollars|23-dec-1999|Idaho")
    ===>
    "Dollars"

    (get-field-of-line 3 "|2|Dollars|23-dec-1999|Idaho")
    ===>
    "23-dec-1999"

    (get-field-of-line 4 "|2|Dollars|23-dec-1999|Idaho")
    ===>
    "Idaho"

    (get-field-of-line 5 "|2|Dollars|23-dec-1999|Idaho")
    ===>
    #f

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)