Re: How to implement word wrap

From: "Andrus" <kobruleht2(at)hot(dot)ee>
To: "Alban Hertroys" <dalroi(at)solfertje(dot)student(dot)utwente(dot)nl>
Cc: "Thom Brown" <thombrown(at)gmail(dot)com>, <pgsql-general(at)postgresql(dot)org>
Subject: Re: How to implement word wrap
Date: 2010-04-03 18:58:36
Message-ID: 47ADDA2F352D46798D7B7635CDEBA1FC@andrusnotebook
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

> Really, write a stored procedure that accepts (text, line_length) and
> returns SETOF text. You could even add hyphenation for the appropriate
> language if you go that route. For the latter it's probably best to write
> it in C so you can link hyphenation libraries to your code.
>
> Another approach that may be viable is to use windowing functions, but I'm
> not so sure it's possible to have a window that is being defined by the
> data it's running over (eg. a window defined by the length of an
> accumulated line of text).

Implementations from http://sqlserverpedia.com/wiki/Word_Wrap_a_String
and from http://docstore.mik.ua/orelly/oracle/prog2/ch11_02.htm#AUTOID-10508
paragraph 11.2.2 did not work in Postgres.
I created method below. Is this best code for this ?

Andrus.

CREATE OR REPLACE FUNCTION wordwrap(line text, linelen integer)
RETURNS SETOF text as $$
DECLARE
words text[] := string_to_array(line,' ');
i integer;
res text:='';

BEGIN
if trim(line)='' then
return next '';
return;
end if;
for i IN 1 .. array_upper(words,1) LOOP
if length(res)+length(words[i]) > linelen THEN
return next res;
res := '';
END IF ;
if res<>'' then
res := res || ' ';
end if;
res := res || words[i];
end loop;
return next res;
END
$$ LANGUAGE plpgsql;

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Scott Bailey 2010-04-03 19:02:03 Re: count function alternative in postgres
Previous Message Lew 2010-04-03 17:47:50 Re: Connection Pooling