You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Delphi代码逻辑看似正确,为何触发Range Check Error?

Delphi代码Range Check Error问题排查与修复

问题场景

执行以下统计文本中点号数量的Delphi代码时,触发了Range Check Error:

unit Unit1;

interface

uses
  System.Classes, Vcl.Controls, Winapi.Messages, System.SysUtils, System.Variants, Vcl.Graphics,
  Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,System.StrUtils;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  i:integer;
  Cnt:integer;
  s:string;
begin
  Cnt := 0;
  s := Edit1.Text;
  for i := 0 to Length(s) do
    if s[i] =  '.' then
       Cnt := Cnt + 1;
  ShowMessage(IntToStr(Cnt));
end;

end.

错误原因

Delphi中字符串的索引从1开始,而非0。你的循环从i:=0开始,访问s[0]直接触发范围检查错误;同时循环结束条件设为Length(s),当字符串为空时,Length(s)=0,循环仍会执行i=0的情况,同样触发越界。

修正后的代码

将循环的起始索引改为1,结束索引保持Length(s)即可解决问题:

procedure TForm1.Button1Click(Sender: TObject);
var
  i:integer;
  Cnt:integer;
  s:string;
begin
  Cnt := 0;
  s := Edit1.Text;
  // 修改循环范围:从1开始到字符串长度
  for i := 1 to Length(s) do
    if s[i] =  '.' then
       Cnt := Cnt + 1;
  ShowMessage(IntToStr(Cnt));
end;

补充说明

如果要更简洁地实现统计功能,也可以使用System.StrUtils单元中的OccurrencesOf函数,一行代码完成统计:

ShowMessage(IntToStr(OccurrencesOf('.', s)));

内容的提问来源于stack exchange,提问作者SangPro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 07:45:51