How to count how many numbers there are in a string?

Hi,
Basically I have in a script:
I need Matlab to say '3' in this example.
Any ideas?

2 Kommentare

What is the definition of 'a number'? Are 123.456, 1e7, 4*i numbers? Or is it just integers?
Stephen23
Stephen23 am 12 Jan. 2015
Bearbeitet: Stephen23 am 12 Jan. 2015
Here are some different ways of writing numbers: do we need to detect them all?:
  • 3
  • 3.14159
  • +3
  • 1.23E-16
  • 0XF3C
  • 001110101
  • Inf
  • two
  • 4/3
  • 75%

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Star Strider
Star Strider am 11 Jan. 2015
This works:
n = length(strsplit(st(~isletter(st))))-1;

Weitere Antworten (1)

Azzi Abdelmalek
Azzi Abdelmalek am 11 Jan. 2015
str='a b c 45 3 2'
out=numel(regexp(str,'\d+','match'))

3 Kommentare

John D'Errico
John D'Errico am 11 Jan. 2015
Bearbeitet: John D'Errico am 11 Jan. 2015
As long as you don't go overboard.
str='a b c 45 3 2 1e12';
out=numel(regexp(str,'\d+','match'))
out =
5
And does inf (or pi) count as a number? MATLAB thinks they are.
isnumeric(inf)
ans =
1
I know, I know, I suppose pi is not a number either. It just represents a number. But the fact is, 2 just represents a number also.
steve
steve am 20 Jan. 2015
thanks for the answer. how can I explain what it means? I've never seen any of those functions and only numel and redexp come up in the help
Ced
Ced am 20 Jan. 2015
That's because these are the only two functions there. You can find a list and description of the different input arguments of e.g. regexp in the documentation: Regexp Documentation

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 11 Jan. 2015

Bearbeitet:

am 21 Jan. 2015

Community Treasure Hunt

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

Start Hunting!

Translated by