Detect if string contains a float?

早过忘川 提交于 2019-12-23 03:05:34

问题


How can I detect if a string contains a float. For example: '0.004'

But without using StrToFloat because that function are slow but rather by iterating through chars.

function IsInteger(const S: String): Boolean;
var
  P: PChar;
begin
  P := PChar(S);
  Result := True;
  while not (P^ = #0) do
  begin
    case P^ of
      '0'..'9': Inc(P);
    else
      Result := False;
      Break;
    end;
  end;
end;

This will check if string is a positive integer but not a float..


回答1:


I would use TryStrToFloat():

if TryStrToFloat(str, value, FormatSettings) then
  ....

If you are prepared to use the default system wide format settings then you can omit the final parameter:

if TryStrToFloat(str, value) then
  ....



回答2:


Can you use a RegEx here? Something like:

([+-]?[0-9]+(?:\.[0-9]*)?) 



回答3:


The problem with this question is that saying "is too slow" doesn't tell much. What does the profiler tells to you? Do you have an informed idea about the input data? What about different notations, for example, 6.02e23?

If your input data is mostly noise, then using regular expressions (as answered here) may improve things but only as a first filter. You could then add a second step to actually obtain your number, as explained by David's answer.



来源:https://stackoverflow.com/questions/20229105/detect-if-string-contains-a-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!