有一些这样的字符串:10cm, 2.5", 8m/m等,想要转成数值型,结果是:10 ,2.5 ,8,我用strtoint语句出现错误,盼高手解决

解决方案 »

  1.   

    你直接用IntToStr来转换这些字符串当然会出错,因为它们含有非数字字符啊!
      

  2.   

    unit Unit1;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls,IdGlobal;type
      TForm1 = class(TForm)
        Button1: TButton;
        procedure Button1Click(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
         function GetNumbystr(str :string) :real;
      end;var
      Form1: TForm1;implementation{$R *.dfm}function TForm1.GetNumbystr(str: string): real;//取出字符串开头的数字
    var
      p   : pchar;
      i   : integer;
      c   : char;
      strVal,strTemp : string;
      pos :integer;
    begin
      strVal := Trim(str);  if Length(strVal)<=0 then
      begin
        Result := 0;
        exit;
      end;
      pos := length(strVal);
      for i := 0 to length(strVal) - 1 do
      begin
        p := Pchar(strVal);
        c := p[i];
        if not IsNumeric(c) then
        begin
            SetLength(strTemp,1);
            strTemp :='.';
            if strTemp <> c then
            begin
              pos := i;
              break;
            end;
        end;
      end;  Result := strtofloat(copy(strVal,0,pos));end;procedure TForm1.Button1Click(Sender: TObject);
    var
       str :string;
    begin
      str :='10cm/m';
      showmessage(floattostr(GetNumbystr(str)));
    end;end.