我正在编写此函数,其中 如果字符串仅相差一个字符,则返回不同的字符位置 ,如果它们是正确的,那么在它们相差超过 1 个字符的情况下,应该返回 -1 和 -10。
仅供引用,'010'
和 '110'
或 '100'
和 '110'
效果很好,每个返回 0 和 1 ......
但是,当我尝试使用 '100'
和 '101'
或与 '110'
和 '111'
当它应该是 2 时,我得到 -1 的结果!我已经完成了桌面测试,但我不能只看到错误。
function combine (m1, m2 : string) : integer;
var
dash : integer;
distinct : integer;
i : integer;
begin
distinct := 0;
dash := -1;
for i := 0 to Length(m1)-1 do
begin
if m1[i] <> m2[i] then
begin
distinct := distinct+1;
dash := i;
if distinct > 1 then
begin
result:= -10;
exit;
end;
end;
end;
result := dash;
end;
我总是得到相同长度的字符串,
我究竟做错了什么?
最佳答案
主要问题是 Delphi 字符串是从 1 开始的。您的循环需要从 1
运行至Length(m1)
.
如果您在编译器选项中启用了范围检查,那么编译器会在运行时引发错误,这会导致您出错。我不能强调你应该启用范围检查。这将导致编译器在您的代码中发现错误。
另请注意,这意味着返回的值也将基于 1。所以输入 '100', '101'
将给出结果 3
因为这是第一个差异的索引。
您还应该检查 m1
和 m2
是相同的长度。如果不引发异常。
另一个提示。将变量增加 1 的惯用方法如下:
inc(distinct);
如果你想增加一个不同的值,写:
inc(distinct, n);
所以,我会这样写函数:
function combine(const m1, m2: string): integer;
var
i: integer;
dash: integer;
distinct: integer;
begin
if Length(m1)<>Length(m2) then begin
raise EAssertionFailed.Create('m1 and m2 must be the same length');
end;
distinct := 0;
dash := -1;
for i := 1 to Length(m1) do
begin
if m1[i] <> m2[i] then
begin
inc(distinct);
dash := i;
if distinct > 1 then
begin
result := -10;
exit;
end;
end;
end;
result := dash;
end;
关于delphi - Delphi中的结果值逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17186623/