Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether a string represents an integer?

I need to determine if a string contains just an integer. The built-in function isinteger is not working.

To avoid loops I'd like to apply this task on cell arrays of strings. For example:

Q = { 'qf5' ; '4' ; 'true' ; 'false' ; '4.00' ; '4E0' ; '4e0' ; '657' }; 

desired result:

integers = 0  1  0  0  0  0  0  1

For a single string I figured out an ugly workaround, but I can't imagine that this is the only possible way, and also it requires a loop to use it on cell arrays:

myString = '4';
integer = uint64( str2double( myString ) );
newString = int2str( integer );
isStringInteger = strcmp(newString,myString);

Which essential function am I missing?

like image 259
Robert Seifert Avatar asked Dec 20 '25 10:12

Robert Seifert


1 Answers

You can do it with regexp; and to avoid the loop you use cellfun:

~cellfun('isempty', regexp(Q, '^-?\d+$'))

This considers an "integer" as a string of digits, possibly with one minus sign at the beginning.

Note that cellfun with the builtin function 'isempty' is very fast.

like image 189
Luis Mendo Avatar answered Dec 23 '25 02:12

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!