What is the fastest way to determine whether a string is a number?
91 次查看(过去 30 天)
显示 更早的评论
Hi, I have a string x and in order to determine wether it is a number one can do the following
try
flag = isnumeric(eval(x));
catch
flag=false;
end
Is there a better and faster way to do this?
Thanks
Pat.
0 个评论
采纳的回答
Sean de Wolski
2014-7-3
编辑:Sean de Wolski
2014-7-3
Probably:
isnan(str2double(str))
This won't need try/catch either.
Anything with eval in it will definitely not be fast.
更多回答(1 个)
Cedric
2014-7-3
编辑:Cedric
2014-7-3
The following should be quite fast (faster than STR2DOUBLE for example):
flag = ~isempty( sscanf( x, '%f' )) ;
EDIT: if characters can appear only at the end of the string, the following will be very fast
flag = x(end) >= '0' && x(end) <='9'
6 个评论
Cedric
2014-7-4
编辑:Cedric
2014-7-4
Can these numbers be floating point or are they integers only? Can they be negative?
Most important, do you really need to optimize further than STR2DOUBLE? The latter is certainly the most straightforward approach; most alternatives would be tricks based on some assumption(s).
For example, if you are only dealing with positive integers, the following will be quite fast
flag = all(x >= '0') && all(x <= '9') ;
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!