2006. október 28., szombat

How to split and concatenate lines of strings in a file


Problem/Question/Abstract:

I have a disk file with lines of 80 character length. I want to concatenate all these lines in one and later split them again into 80 character lines. How can I do this?

Answer:

function GetOneString(const FilePath: string): string;
var
  List: TStringList;
  i: Integer;
begin
  Result := '';
  List := TStringList.Create;
  try
    try
      list.LoadFromFile(FilePath);
    except
    end;
    for i := 0 to List.Count - 1 do
      Result := Result + List[i];
  finally
    list.free;
  end;
end;

To save to a file:

procedure SaveStrings(const FilePath: string; const Num: Integer; St: string);
{FilePath: Name of file to save string / Num: Width of strings, 80 in your case / St: String to save}
var
  f: system.text;
  i: Integer;
begin
  assignfile(f, FilePath);
  rewrite(f);
  i := 0;
  while ((i + Num) <= Length(st)) do
  begin
    writeln(f, copy(st, i + 1, Num));
    inc(i, Num);
  end;
  inc(i);
  if (i < Length(st)) then
  begin
    Writeln(f, copy(st, i, Num));
  end;
  closefile(f);
end;

A TStringList has some properties like Text and Commatext which return the complete strings separated by CRLF (CarriageReturn and Line Feed) and ',' respectively, therefore you could use any of these to access the strings without wasting extra resources.

Nincsenek megjegyzések:

Megjegyzés küldése