« Reply #16 on: September 12, 2025, 08:36:42 am »
This is my take:
program tabexpander;
{$ifdef fpc}{$mode objfpc}{$endif}{$H+}
uses sysutils;
operator in (v:char;s:string):Boolean;inline;
begin
result := pos(v, S) <> 0;
end;
function expandtabs(const s:ansistring;tabsize:byte = 8):ansistring;inline;
begin
Result := s;
while #9 in result do
result := stringreplace(Result,#9,stringofchar(#32,tabsize - (pos(#9,result)-1) mod tabsize),[]);
end;
begin
WriteLn('"', ExpandTabs('1234567'#9'abc'), '"');
WriteLn('"', ExpandTabs('123456'#9'abc'), '"');
WriteLn('"', ExpandTabs('123'#9'abc'), '"');
WriteLn('"', ExpandTabs('1'#9'abc'), '"');
WriteLn('"', ExpandTabs(#9'abc'), '"');
WriteLn('"', ExpandTabs('123456781234567812345678'), '"');
WriteLn('"', ExpandTabs('1234'#9'abcd'#9'xyz'), '"');
WriteLn('"', ExpandTabs('abc'#9#9'abc'), '"');
WriteLn('"', ExpandTabs(#9#9'abc'), '"');
WriteLn('"', ExpandTabs('abc'#9), '"');
WriteLn('"', ExpandTabs('abc'#9#9), '"');
WriteLn('"', ExpandTabs('abc'#9'abc'#9), '"');
ReadLn;
end.
Identical output as @wp
There is a bug in my code: tabsize can not be 0. Some other solutions - e.g. Jamie's - have the same issue: modulo 0 = division by zero.
To correct that:
function expandtabs(const s:ansistring;tabsize:byte = 8):ansistring;inline;
begin
Result := s;
case tabsize of
0:result := stringreplace(result,#9,'',[rfReplaceAll]);
1:result := stringreplace(result,#9,#32,[rfReplaceAll]);
2..255:while #9 in result do
result := stringreplace(Result,#9,stringofchar(#32,tabsize - (pos(#9,result)-1) mod tabsize),[]);
end;
end;
« Last Edit: September 12, 2025, 10:27:15 am by Thaddy »

Logged
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.