How do I call the first number in a string?

38 views (last 30 days)
Morgan Minton
Morgan Minton on 20 Jun 2014
Edited: Cedric on 20 Jun 2014
Is there a function/process that I can use to call the first number in a string? Example:
string='hello123'
f=fun(string)
f=
1
I would simply call for the 5th character in the string to find 1, but the length of the string is user defined and can be any number of characters in length. The value of the first number in the string will determine an output later on. Like if f==1, do this, else , do that sort of thing.
Thanks

Answers (2)

Cedric
Cedric on 20 Jun 2014
Edited: Cedric on 20 Jun 2014
If the text just contains letters followed by numbers, an efficient way to proceed is as follows;
num = string - '0' ;
f = num(find( num >= 0 & num < 10, 1 )) ;
If you really need a function, we can update this answer. We could also use a more 'regular' - yet less efficient - type of approach, e.g.
f = str2double( regexp( string, '\d', 'match', 'once' )) ;

Joseph Cheng
Joseph Cheng on 20 Jun 2014
I do not think there is a built in function but you can write a loop to determine what the first number is.
for i =1:length(text)
if ~isempty(str2double(text(i)))
first_number = i
break
else
first_number = [];
end
end

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!