Delphi使用for循环创建字母



如您所知,Excel中的列名是字母。当它到达Z时,它继续AA-AB-AC。是否可以在DelphiXE7+中为循环创建类似的函数?

我试过:

var
i:integer;
str:string;
begin
str:='a';
for i := 0 to 26-1 do
begin
inc (str,1);
memo1.Lines.Add(str);
end;

但它回来了:

[dcc32 Error] FBarkodsuzIndesignVerisiOlustur.pas(249): E2064 Left side cannot be assigned to

我想这是因为str不是整数。

我可以用这个功能将数字转换为字母:

function numberToString(number: Integer): String;
begin
Result := '';
if (number < 1) or (number > 26) then
Exit;
Result := 'abcdefghijklmnopqrstuvwxyz'[number];
end;

但我不知道当AA超过26时,我们如何才能创建这样的字母。

同样使用下面的方法,它可以创建26个字母,但当它超过26个时,它开始使用括号之类的字符:

for i := 0 to 27-1 do
begin
memo1.Lines.Add(Char(Ord('a') + i));
end;

输出:

a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
{

当它到达Z时,它将继续作为"Z";AA"BB"CC";等等,就像Excel创建列名一样。

这是我用于任务的函数。

function SpreadSheetColName(const Col: Integer): string;
var
c: Char;
begin
Assert(Col >= 0);
if Col<26 then begin
c := 'A';
Inc(c, Col);
Result := c;
end else begin
Result := SpreadSheetColName(Col div 26 - 1) + SpreadSheetColName(Col mod 26);
end;
end;

请注意,它使用基于零的索引。我建议您在整个编程过程中也使用基于零的索引作为一般规则。

如果你不能让自己做到这一点,那么一个基于一个的版本会是这样的:

function SpreadSheetColName(const Col: Integer): string;
function SpreadSheetColNameZeroBased(const Col: Integer): string;
var
c: Char;
begin
Assert(Col >= 0);
if Col<26 then begin
c := 'A';
Inc(c, Col);
Result := c;
end else begin
Result := SpreadSheetColNameZeroBased(Col div 26 - 1) + SpreadSheetColNameZeroBased(Col mod 26);
end;
end;
begin
Result := SpreadSheetColNameZeroBased(Col - 1);
end;

最新更新