How do I call the first number in a string?
Mostrar comentarios más antiguos
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
Respuestas (2)
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
el 20 de Jun. de 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
Categorías
Más información sobre Characters and Strings en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!