-3

I have a string,

"This is my id 4321."

Now how to extract only number part "4321" from the whole string using c++. Thank you.

njporwal
  • 131
  • 2
  • 4
  • 9

1 Answers1

7

You can use atoi and isdigit:

// Example string
std::string str = "this is my id 4321.";

// For atoi, the input string has to start with a digit, so lets search for the first digit
size_t i = 0;
for ( ; i < str.length(); i++ ){ if ( isdigit(str[i]) ) break; }

// remove the first chars, which aren't digits
str = str.substr(i, str.length() - i );

// convert the remaining text to an integer
int id = atoi(str.c_str());

// print the result
std::cout << id << std::endl;
Gombat
  • 1,886
  • 16
  • 21