Re: [HACKERS] substring extraction

From: Karel Zak - Zakkr <zakkr(at)zf(dot)jcu(dot)cz>
To: jose soares <jose(at)sferacarta(dot)com>
Cc: pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: [HACKERS] substring extraction
Date: 1999-11-26 14:36:45
Message-ID: Pine.LNX.3.96.991126151247.30394A-100000@ara.zf.jcu.cz
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Fri, 26 Nov 1999, jose soares wrote:

> Try this:
>
> --returns the $2 field delimited by $3
> drop function field(text,int,text);
> create function field(text,int,text) returns text as
> 'declare
> string text;
> pos int2:= 0;
> pos1 int2:= 0;
> times int2:= 0;
> totpos int2:= 0;
> begin
> times:= $2 - 1;
> string:= $1;
> while totpos < times loop
> string:= substr(string,pos+1);
> pos:= strpos(string,$3);
> totpos:= totpos + 1;
> end loop;
> string:= substr(string,pos+1);
> pos1:= strpos(string,$3);
> return substr(string,1,pos1 - 1);
> end;
> ' language 'plpgsql';
>

Oh, it is great! But my implementation in C for this is
a little longer (only) :-)

I send this question to the hacker list because "extract delimited
substring" is not a abnormal uses's request, and (IMHO) will very
good if this will in PgSQL. How much uses known write this in
C or any PL?

'C' implementafion "extract delimited substring":
-----------------------------------------------
text
*strcut( text *string, char *d, int field )
{
char *ptr = NULL,
*p = NULL,
*pe = NULL;
text *result = NULL;
int siz;

ptr = VARDATA(string);
*(ptr+ (VARSIZE(string) - VARHDRSZ)) = '\0';

for(p = ptr; *p != '\0'; p++) {
if (field == 1)
break;
if (*p == (int) d)
--field;
}
if (!*p)
return textin("");

for(pe = p; *pe != '\0'; pe++) {
if (*pe == (int) d)
break;
}

result = (text *) palloc(sizeof(text) * (siz = pe - p) + VARHDRSZ);
strncpy(VARDATA(result), p, siz);

*(VARDATA(result) + siz) = '\0';
VARSIZE(result) = siz + VARHDRSZ;
return result;
}

CREATE FUNCTION strcut(text, char, int)
RETURNS text
AS '@module_dir@'
LANGUAGE 'c';

template1=> select strcut('aaa.bbb.ccc', '.', 2);
strcut
------
bbb

Karel

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Tom Lane 1999-11-26 15:38:06 Re: pg_ctl
Previous Message Grzegorz Przeździecki 1999-11-26 14:30:03 Re: [HACKERS] Vacuum