### 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 ?

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
 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364`` ``````// simple char-by-char parsing example #include #include using namespace std; int main(void) { int i=0, n=0, x=0; // input string string sTestString("22 + 4- 17"); // output containers // using vector 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.