Archive
Archive for June 17, 2014
Smart ExplodeStr() implementation
June 17, 2014
Leave a comment
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