Delphi中用状态图对字符串数据进行类型判断

王朝delphi·作者佚名  2006-01-31
窄屏简体版  字體: |||超大  

Delphi中用状态图对字符串数据进行类型判断

在我们写程序时总是会遇到对字符串进行数据类型判断,如:整型,浮点型等。而我们可是用状态图<图1>的方法来对字符串数据进行类型判断。

对字符串进行类型判断我们一般需要对它进行解析,在解析过程中我们需要标识出它现在的状态和下次它可以出现在状态,如整型,浮点型。在解析完后我们可以得出它最后的状态,这样我们对它的类型判断的结果就是它那个最后的状态,通过这个我们可以达到举一反三的效果。

图1

图中有五个小圆圈表示五种状态(虚线的圆圈表示中间状态,实线圆圈表示最终状态。当然还有一种状态我没有画出来:非数据类型),它们分别是:StateInit(开始),StateDiag(符号),stateDot(小数点),StateInt(整型),stateFloat(浮点型),箭头表示字符串的解析流程,长方型表示解析的每个字符。

我们举个例子来说说吧!如字串:”-19.2”。把它解析成‘-’→‘1’→‘9’→‘.’→‘2’。根据图1:开始状态为stateInit,解析第一个字符‘-’ →得到它的状态为StateDiag,

解析第二个字符‘1’ →得到它的状态为StateInt,解析字符‘9’ →得到它的状态为StateInt,解析字符‘。’→得到它的状态为StateFloat→…→得到它最后的状态为StateFloat。这样我们就得到了最终结果:这个字符串对应的是浮点型的数据。下面是Delphi源码<仅供参考>:

{******************************

//author = py

//time = 20/06/04

//function = Is integer(float) or not in string;

*******************************}

unit Pfunction;

interface

//uses windows;

{*result: 0. Integer

* 1. float

* -1. error}

function isNumberOrFloat(aEnterStr: PChar): Integer;

implementation

function isNumberOrFloat(aEnterStr: PChar): integer;

function isNumber(aNum: char): boolean;

begin

result := false;

if (aNum >= '0') and (aNum <= '9') then

result := true;

end;

function isSymbol(aNum: char): boolean;

begin

result := false;

if ((aNum = '+') or (aNum = '-')) then

result := true;

end;

function isDot(aNum: char): boolean;

begin

result := false;

if (aNum = '.') then

result := true;

end;

type TStateBit = (STATEINIT, STATEINT, STATEDIAG,

STATEDOT, STATEFLOAT, ERROR); //static enum

var mCh: char; // char of string

mI: integer; //circle num

mInx: integer; //length of string;

mState: TStateBit ; //current state

begin

mInx := Length(aEnterStr);

mState := STATEINIT;

result := -1;

for mI := 0 to mInx-1 do

begin

mCh := aEnterStr[mI];

case mState of

STATEINIT:begin

if isNumber(mCh) then begin

mState := STATEINT;

end

else if (isSymbol(mCh)) then begin

mState := STATEDIAG;

end

else if isDot(mCh) then begin

mState := STATEDOT;

end

else mState := ERROR;

end;

STATEINT: begin

if isDot(mCh) then begin

mState := STATEFLOAT;

end

else if (isNumber(mCh))then begin

mState := STATEINT;

end

else mState := ERROR;

end;

STATEDIAG:begin

if isNumber(mCh) then begin

mState := STATEINT;

end

else if isDot(mCh) then begin

mState := STATEDOT;

end

else mState := ERROR;

end;

STATEDOT: begin

if isNumber(mCh) then begin

mState := STATEFLOAT;

end

else mState := ERROR;

end;

STATEFLOAT:begin

if isNumber(mCh) then begin

mState := STATEFLOAT;

end

else mState := ERROR;

end;

end;

end;

if (mState = STATEINT) then result := 0

else if (mState = STATEFLOAT) then result := 1;

end;

end.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航