我已经读了一个文本文件(名称)到一个数组中,我需要如何将这些名称按字母顺序排序,并在丰富的编辑中显示?我真的需要帮助德尔福...文本文件和数组与排序?
请给我的代码从这时开始:
readln(MYFILE,编曲[1]);
'myfile'是文本文件,'arr'是字符串数组。 另外,我已经声明'i'是一个整数,即使它是一个字符串数组。这可以吗?
我已经读了一个文本文件(名称)到一个数组中,我需要如何将这些名称按字母顺序排序,并在丰富的编辑中显示?我真的需要帮助德尔福...文本文件和数组与排序?
请给我的代码从这时开始:
readln(MYFILE,编曲[1]);
'myfile'是文本文件,'arr'是字符串数组。 另外,我已经声明'i'是一个整数,即使它是一个字符串数组。这可以吗?
使用StringList,然后很容易。 StringList也可以自动排序。 查看示例(滚动一路向下): http://www.delphibasics.co.uk/Article.asp?Name=Files
使用TStringList而不是数组并将Sort属性设置为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;
names.free应该是sortlist.free,并且您应该尝试..最终保护物体。 – 2010-05-18 21:17:49
总是尝试...终于! – 2010-05-18 21:38:15
这假定名称是文件中的唯一内容,这可能是也可能不是一个正确的假设。 – Deltics 2010-05-19 03:57:44
对不起。我不能帮助它... ...
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.
如果你是一个新手:Welcome, and good luck with Delphi.
如果你在一个严重的项目工作:
满分! :-) – 2011-07-25 20:34:26
家庭作业? – dthorpe 2010-05-18 21:32:43
有关使用TStringList的回复是正确的。至于你关于将** i **声明为整数的问题,即使数组是字符串类型,是的,这是正确的。 **我**没有引用数组的元素,它是数组的*索引*,并且数组总是通过整数值进行索引。 (有些对象具有索引属性,可以通过其他数据类型(如字符串)进行索引,但普通数组总是以整数索引。) – 2010-05-18 23:04:00