Hello everyone, while scripting today i came across the need for sprintf() and as far as i know there is no sprintf() style function in pascal, so here is my rendition. It should be pretty efficient, and its pretty easy to add new keywords/types.
Usage:
var finalstring: string;
finalstring := sprintf('my int=%i%, my float=%f%, my string=%s%',[15,1.2345,'abcd']);
// finalstring = 'my int=15, my float=1.2345, my string=abcd
Warning:
You must have the same amount of item tokens('%i%') as array elements.
The Code:
function sprintf(Mask: string; Input: array of variant): string;
var cur,add: string; i,ii: integer;
begin
result := '';
i := 0;
ii := 0;
cur := getpiece(mask,'%',i);
while (cur <> nil) do begin
if i mod 2 = 0 then begin
add := cur;
end else begin
cur := lowercase(cur);
add := 'ERROR';
case cur of
's': add := input[ii];
'i': add := inttostr(input[ii]);
'd': add := floattostr(input[ii]);
'f': add := floattostr(input[ii]);
end;
ii := ii + 1;
end;
i := i + 1;
cur := getpiece(mask,'%',i);
result := result + add;
end;
end;
EDIT:
Also ill post this, it gets filenames that ascend in order, like backup_0,backup_1,backup_2 ect. It uses sprintf() above.
Usage:
var myfilename: string;
myfilename := getsequentialfilename('scripts/'+scriptname+'/gamesave_%i%.txt',5);
The above usage code will result in available filenames like this:
'scripts/<scriptname>/gamesave_0.txt'
'scripts/<scriptname>/gamesave_1.txt'
'scripts/<scriptname>/gamesave_2.txt'
'scripts/<scriptname>/gamesave_3.txt'
'scripts/<scriptname>/gamesave_4.txt'
If there are no available filenames in the rage provided the function returns a null string, '', or nil.
The Code:
function GetSequentialFilename(Mask: string; Max: integer): string;
var i: integer; newname: string;
begin
result := '';
i := 0;
while true do begin
newname := sprintf(mask,[i]);
if not fileexists(newname) then break;
if i >= max-1 then exit;
i := i + 1;
end;
result := newname;
end;
What do you think, usefull or not?