Skip to content

Instantly share code, notes, and snippets.

@jarroddavis68
Last active April 7, 2022 00:12
Show Gist options
  • Save jarroddavis68/71c22aed2aafe57430ad6585e09fc323 to your computer and use it in GitHub Desktop.
Save jarroddavis68/71c22aed2aafe57430ad6585e09fc323 to your computer and use it in GitHub Desktop.
TSpStringList - Enhanced Delphi String List
unit uSpStringList;
interface
uses
System.SysUtils,
System.Classes;
type
{ TSpStringList }
TSpStringList = class(TStringList)
protected
function ValidIndex(aIndex: Integer): Boolean;
public
function GetLineIndex(aOccurrence: Cardinal; const aLine: string): Integer;
function ReplaceLine(aOccurrence: Cardinal; const aOldLine: string; const aNewLine: string; aOffset: Integer): Boolean;
function RemoveLines(aOccurrence: Cardinal; const aReferenceLine: string; aOffset: Integer; aCount: Cardinal): Boolean;
function InsertLine(aOccurrence: Cardinal; const aReferenceLine: string; aOffset: Integer; const aNewLine: string): Boolean;
end;
implementation
uses
System.StrUtils;
{ TSpStringList }
function TSpStringList.ValidIndex(aIndex: Integer): Boolean;
begin
Result := False;
if aIndex < 0 then Exit;
if aIndex > Self.Count-1 then Exit;
Result := True;
end;
function TSpStringList.GetLineIndex(aOccurrence: Cardinal; const aLine: string): Integer;
var
LIndex: Integer;
LText: string;
LOccurence: Cardinal;
begin
Result := -1;
if aOccurrence = 0 then Exit;
LOccurence := 0;
for LIndex := 0 to Self.Count-1 do
begin
LText := Self[LIndex].Trim;
if SameText(aLine, LText) then
begin
Inc(LOccurence);
if LOccurance = aOccurence then
begin
Result := LIndex;
Exit;
end;
end;
end;
end;
function TSpStringList.ReplaceLine(aOccurence: Cardinal; const aOldLine: string; const aNewLine: string; aOffset: Integer): Boolean;
var
LIndex: Integer;
begin
Result := False;
LIndex := GetLineIndex(aOccurance, aOldLine);
if LIndex = -1 then Exit;
LIndex := LIndex + aOffset;
if not ValidIndex(LIndex) then Exit;
Self[LIndex] := aNewLine;
Result := True;
end;
function TSpStringList.RemoveLines(aOccurence: Cardinal; const aReferenceLine: string; aOffset: Integer; aCount: Cardinal): Boolean;
var
LIndex: Integer;
LStartIndex: Integer;
begin
LStartIndex := GetLineIndex(aOccurance, aReferenceLine);
if LStartIndex = -1 then Exit;
LStartIndex := LStartIndex + aOffset;
if not ValidIndex(LStartIndex) then Exit;
for LIndex := 1 to aCount do
Self.Delete(LStartIndex);
Result := True;
end;
function TSpStringList.InsertLine(aOccurence: Cardinal; const aReferenceLine: string; aOffset: Integer; const aNewLine: string): Boolean;
var
LIndex: Integer;
begin
Result := False;
LIndex := GetLineIndex(aOccurance, aReferenceLine);
if LIndex = -1 then Exit;
LIndex := LIndex + aOffset;
if not ValidIndex(LIndex) then Exit;
Self.Insert(LIndex, aNewLine)
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment