Re: piece function - there must be an easier/more elegant way !?

new topic     » goto parent     » topic index » view thread      » older message » newer message

I don't know about "more elegant" but here's anither attempt...

--------------------
function piece(sequence s, integer delimiter, integer position)

    integer  startat, endat

    -- Ensure the string always ends with a delimiter
    s = append(s,delimiter)

    -- initialize
    startat = 1
    endat = 1

    -- look at each substring
    while position > 0 do

        -- find the end of the current substring
        endat = find(delimiter, s)

        -- If it doesn't end, then return nothing
        if endat = 0 then
                return ""
        end if

        -- remove the delimiter
        s[endat] = delimiter + 1

        -- indicate I've finished with this substring
        position -= 1

        -- if there are any more to scan for, updated the start locn.
        if position > 0 then
            startat = endat + 1
        end if
    end while

    -- return the substring
    return s[startat .. endat - 1]
end function
-----------------
Derek Parnell
Melbourne, Australia
"To finish a job quickly, go slower."

----- Original Message -----
From: <freeplay at mailandnews.com>
To: "EUforum" <EUforum at topica.com>
Sent: Monday, May 14, 2001 10:55 PM
Subject: piece function - there must be an easier/more elegant way !?


>
>
> Hello folks,
>
> Attached is a short text file containing a function I've called piece.
>
> It takes three arguments, a string sequence, a delimiter character and an
> integer index.  Using the delimter character it chops the string into
pieces
> and returns the one specified by the integer index.  The integer index
begins
> at 1.
>
> Hence:
>
> sequence s
> s = "andy:1:hello there::ok"
>
> printf(1, "%s", {piece(s, ':', 1)})
>
> gives "andy"
>
> printf(1, "%s", {piece(s, ':', 2)})
>
> gives "1"
>
> printf(1, "%s", {piece(s, ':', 3)})
>
> gives "hello there" and
>
> printf(1, "%s", {piece(s, ':', 4)})
>
> gives the null string "".
>
> Asking for a piece out of range will also give "".
>
> I think the way I've coded this is rather bad - there must be a more
elegant
> solution.  Any offers?  I've thought of strtok.e in the archives but it
might
> be a little overkill for my needs.
>
> Note I needed to put the code in an attached text file as my web based
mailer
> messes up code indentation something rotton.
>
> Best regards,
>
> FP.
>
>
>
>

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu