going through a string of characters and extracting the numbers?
Given a string of characters, how can I go through it and assign all the numbers within that string into an integer variable, leaving out all ot开发者_高级运维her characters?
I want to do this task when there is a string of characters already read in through gets()
, not when the input is read.
unsigned int get_num(const char* s) {
unsigned int value = 0;
for (; *s; ++s) {
if (isdigit(*s)) {
value *= 10;
value += (*s - '0');
}
}
return value;
}
Edit: Here is a safer version of the function.
It returns 0 if s
is NULL
or cannot be converted to a numeric value at all. It return UINT_MAX
if the string represents a value larger than UINT_MAX
.
#include <limits.h>
unsigned int safe_get_num(const char* s) {
unsigned int limit = UINT_MAX / 10;
unsigned int value = 0;
if (!s) {
return 0;
}
for (; *s; ++s) {
if (value < limit) {
if (isdigit(*s)) {
value *= 10;
value += (*s - '0');
}
}
else {
return UINT_MAX;
}
}
return value;
}
This is a simple C++ way to do that:
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char* argv[]) {
istringstream is("string with 123 embedded 10 12 13 ints", istringstream::in);
int a;
while (1) {
is >> a;
while ( !is.eof() && (is.bad() || is.fail()) ) {
is.clear();
is.ignore(1);
is >> a;
}
if (is.eof()) {
break;
}
cout << "Extracted int: " << a << endl;
}
}
Look up the strtol
function from the standard C library. It allows you to find the part of a character array that is a number, and points to the first character that isn't a number and stopped the parsing.
You can use sscanf
: it works like scanf
but on a string (char array).
sscanf
might be overkill for what you want though, so you can also do this:
int getNum(char s[])
{
int ret = 0;
for ( int i = 0; s[i]; ++i )
if ( s[i] >= '0' && s[i] <= '9' )
ret = ret * 10 + (s[i] - '0');
return ret;
}
精彩评论