首页 > 解决方案 > Delphi用for循环创建字母

问题描述

如您所知,Excel 中的列名是字母。当它到达 Z 时,它会继续 AA-AB-AC。是否可以在 Delphi XE7 + for 循环中制作类似的功能?

我试过了:

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;

但我不知道我们如何在超过 26 时创建像 AA 这样的字母。

同样使用以下方法,它可以创建 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 时,它将继续为“AA”“BB”“CC”等等,就像 Excel 创建列名一样。

标签: loopsfor-loopdelphialphabetmemo

解决方案


这是我用于该任务的功能。

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;

推荐阅读