Get numbers out of a string

Hi all,

If I have a string or an array of char like "11a2b" or "22 + 4- 17", is there anyway to get the number 11 and 2 from the first and 22, 4 and 17 from the second ?

Thanks in advance.
you can use isdigit() function.

string xyz("3141y59");
cout<< plugh << '\n';
// This will check for numeric value
for (int i = 0; i < xyz.length(); i++)
{
if (isdigit (xyz[i]))
{
//digit
cout << xyz[i];
}
}

Hope this will useful to you..
Last edited on
in order to use isdigit(), you'll need to include "ctype.h" header file.

Yes,use this but remember it will not give 11 and 22 or 17.
It will give 1,1 or 2,2 or 1,7.

Check it yourself by using this in above code

cout << xyz[i]<<endl;

If you want to get digits only then use this.

If you want whole number then this will not work logically.
yaa of course this is for single digit. For getting whole number you have to apply some logic.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// simple char-by-char parsing example
#include <iostream>
#include <ctype.h>

using namespace std;

int main(void)
{
    int i=0, n=0, x=0;
    
    // input string
    string sTestString("22 + 4- 17");
     
    // output containers
    // using vector<std::string> here would be bestter soluton
    // since you could parse more that 5 arguments
    string sNumbers[5] = {"","","","",""};
    string sChars[5] = {"","","","",""};
    
    // parse input string
    while (sTestString.c_str()[i] != '\0' )
    {
        // char is a digit
        if (isdigit(sTestString.c_str()[i]))
        {
            do // find if the next char is a digit
            {
                sNumbers[n] += sTestString.c_str()[i];
                i++;                
            }while(isdigit(sTestString.c_str()[i]));
            n++;
            i--;
        }
        else // char is not a digit
        {
            if (sTestString.c_str()[i] != ' ') //ignore space
            {
                sChars[x] = sTestString.c_str()[i];
                x++;
            }
        }
        
        i++; //move to next char
    }
    
    // print output
    for (i=0;i<5;i++)
    {
        if (! sNumbers[i].empty())
        {
            cout << sNumbers[i] << endl;
        }
    }
    
    for (i=0;i<5;i++)
    {
        if (! sChars[i].empty())
        {
            cout << sChars[i] << endl;
        }
    }
    
    return 0;
}


This is just an example, it has many flaws, it is not optimized and it is definitely not meant to be used in real life project but to understand parsing process.

..and yes - this program wont work for more that 5 numbers/characters found. You could add some if's but most convenient would be using dynamic arrays like vectors (vector.h).
Topic archived. No new replies allowed.