Read only numbers from string
21 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
SJ Won
el 5 de Jul. de 2019
Comentada: SJ Won
el 8 de Jul. de 2019
Given a string, how to read only the numbers? I am trying to sum them up afterward.
This was my solution:
splitted = strsplit(str)
total = 0;
array = [];
for i=1:numel(splitted)
if ~isnan(str2double(splitted{i}))
array = [array " " splitted{i}]
end
end
total = nansum(str2double(array))
However, this is only assuming the numbers are not attached to any characters. Strings like '42hi' would not be counted.
I then thought about something like this:
multiple_digit = [];
single_digit = [];
k=1;
for ii=1:numel(str)
if isa(str2num(str(ii)), 'double')
if ~isa(str2num(str(ii+1)), 'double') %if next character isn't a number, then puts that number in
single_digit(k) = str2num(str(ii))
end
end
end
I am checking each individual characters in the string to see if it is a number. If it is, then I check to see if the next character is also a number so that I can take a string like '100' as 100, not 1. However, this seems very complicated, as I have to control whether I am going out of the array index or not.
2 comentarios
Stephen23
el 5 de Jul. de 2019
Editada: Stephen23
el 5 de Jul. de 2019
"However, this is only assuming the numbers are not attached to any characters. Strings like '42hi' would not be counted."
What does this mean? Do you want to match that 42 or not?
Your question is missing the most important information of all: an actual specification or example of what the string and number substrings are like. It is very difficult to write code to parse strings given no information about exactly what is in the string, how the numbers are to be identified, etc.
"However, this seems very complicated..."
It is very complicated. Read this:
Respuesta aceptada
Stephen23
el 5 de Jul. de 2019
Editada: Stephen23
el 5 de Jul. de 2019
"Given a string, how to read only the numbers?"
That really depends on what you define as being a "numberˇ: which of these are "numbers" according to your definition?:
- 1
- -1
- +1
- 1.0
- 1e-2
- NaN
- Inf
- 1+2i
- i
- e
- pi
- etc. etc.
If you are only interested in matching integers, then this should get you started:
>> str = '12 3 4';
>> sum(str2double(regexp(str,'\d+','match')))
ans = 19
Más respuestas (0)
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!