我有一個簡單的功能,可以將數字轉換爲字符串(類似於Excel列號1..n
可以轉換爲列名稱A-ZZZ
)。當我使用這個很多時,我已經刪除了局部變量作爲速度優化,並且只能直接使用Result
。如何解決分配字符串到字符串W1047/W1068警告?
當我編譯,我得到這2個警告:
W1047不安全的代碼 '字符串指數爲VAR PARAM' 到位可能不是
W1068修改字符串未來支持
他重新是縮短的功能:
function Idx2Code_(Idx: integer): string;
begin
SetLength(Result, 3); // init Result size
if Idx <= 26 then
begin
// single char: A-Z
Result := Chr(64 + Idx);
SetLength(Result, 1);
end
else if Idx <= 676 then
begin
// 2 chars codes: BA-ZZ
Result[1] := Chr((Idx div 26) + 64 + 1); // <- warnings for this line
Result[2] := Chr((Idx mod 26) + 64); // <- warnings for this line
SetLength(Result, 2);
end
else
begin
// 3 chars codes: BAA-ZZZ
Result[1] := Chr((Idx div 676) + 64 + 1); // <- warnings for this line
Result[2] := Chr(((Idx mod 676) div 26) + 64 + 26); // <- warnings for this line
Result[3] := Chr((Idx mod 26) + 64 + 26); // <- warnings for this line
end;
end;
我可以使用局部變量,但其速度較慢,我不想。
我不想在未來的Delphi版本中使用可能會「過時」的代碼。
我該如何解決警告,但儘可能保持簡單和速度?
它說'E2129無法分配給只讀property'上線'Result.Chars [0]:= CHR(64 + IDX);」。我確實使用了SystemSysutils。我在這裏錯過了什麼? –
我的不好,我忘了'TStringHelper.Chars []'確實是只讀的,你不能用它來修改'string'的內容。我會更新我的答案。 –
@MikeTorrettinni,使用[StringBuilder](http://docwiki.embarcadero.com/Libraries/en/SystemUtils.TStringBuilder.Chars) –