I really need help with Delphi... text files and arrays with sorting?
I have read a text file (of names) into an array and I need how to sort those names into alphabetical order and display that in a rich edit?
Please give me the code from this point onwards:
readln(myfile,arr[i]);
'myfile' is the text file and 'arr' is the array of string. Also, I have declared 'i' as an integer even though it is a array of string. Is that OK?
Use a TStringList instead of a array and set the Sort property to true.
var
sortlist : TStringList; // Define our string list variable
begin
// Define a string list object, and point our variable at it
sortlist := TStringList.Create;
try
// Now add some names to our list
sortlist.Sorted := True;
// And now find Brian's age
sortlist.LoadFromFile(myfile);
// Do something.
finally
// Free up the list object
sortlist.Free;
end;
end;
Use a StringList and then it's easy. StringList can also sort automatically. See an example here (scroll all the way down): http://www.delphibasics.co.uk/Article.asp?Name=Files
Sorry. I couldn't help it...
program BubblesortTextFile;
{$APPTYPE CONSOLE}
uses
SysUtils;
const
MAX = 100;
FILE_NAME = 'C:\Text.txt';
type
TMyRange = 0..MAX;
var
i,j,top: TMyRange;
a: Array[TMyRange] of String;
f: TextFile;
tmp: String;
begin
//Init
i := 0;
//Read all items from file
Assign(f, FILE_NAME);
Reset(f);
while not Eof(f) do
begin
ReadLn(f, a[i]);
Inc(i);
end;
Close(f);
top := i-1;
//Bubble sort (Never use this in real life...)
for i := Low(TMyRange) to top-1 do
for j := i+1 to top do
if a[j] < a[i]
then begin
tmp := a[i];
a[i] := a[j];
a[j] := tmp;
end;
//Print the array
for i := 0 to top do
WriteLn(a[i]);
//Wait for user
ReadLn;
end.
If you're a newbie: Welcome, and good luck with Delphi.
If you're working on a serious project: Get help...
精彩评论