Home > OP4JS, Uncategorized > Smart ExplodeStr() implementation

Smart ExplodeStr() implementation

In PHP there is a neat function called Explode() which takes a string and breaks it down into words, returning an array of strings. This is handy when displaying text and working out word-wrap functionality, so I wrote a Smart Pascal variation of the Explode() function. Simple but handy:

function  ExplodeStr(const aText:String;
          const aRetain:Boolean;
          var aWords:Array of String):Integer;
const
  CNT_INVALID=' ;.,-:&/()*^!' + #13 + #10;
var
  x:      Integer;
  mCache: String;
  mLen: Integer;
begin
  aWords.Clear;
  result:=0;
  mLen:=Length(aText);
  if mLen>0 then
  begin
    x:=0;
    repeat
      inc(x);
      if pos(aText[x],CNT_INVALID)<1 then
      mCache:=mCache + aText[x] else
      begin
        if aRetain then
        mCache:=trim( mCache + aText[x] );
        if length(mCache)>0 then
        begin
          aWords.add(mCache);
          setLength(mCache,0);
        end;
      end;
    until x>mLen;
    result:=aWords.count;
  end;
end;

The retain parameter simply decides if the break character should be included or not. If you want “clean” words then set this to false.

In short, if you do this:

ExplodeStr('this.is.a.test',false,mData);

The mData array contains the following:

mData[0] = this
mData[1] = is
mData[2] = a
mData[3] = test

But if you retain the characters (which you really have to when measuring width/height of a word) then you get this:

mData[0] = this.
mData[1] = is.
mData[2] = a.
mData[3] = test
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: