Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract numbers from string in c?

Tags:

c

string

Say I have a string like ab234cid*(s349*(20kd and I want to extract all the numbers 234, 349, 20, what should I do ?

like image 952
CDT Avatar asked Nov 15 '12 14:11

CDT


People also ask

How do you read numbers in a string?

You can use sscanf here if you know the number of items you expect in the string: char const *s = "10 22 45 67 89"; sscanf(s, "%d %d %d %d %d", numbers, numbers+1, numbers+2, numbers+3 numbers+4);

How do I print numbers in string?

Print out the integers in the string. Run one for loop to read character by character. First, convert this string to an array of characters by using the toCharArray() method and then read each character ony by one using a for loop. Check if the character is a number or not using the isDigit method.


2 Answers

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
    if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
        // Found a number
        long val = strtol(p, &p, 10); // Read number
        printf("%ld\n", val); // and print it.
    } else {
        // Otherwise, move on to the next character.
        p++;
    }
}

Link to ideone.

like image 110
Sergey Kalinichenko Avatar answered Oct 24 '22 21:10

Sergey Kalinichenko


A possible solution using sscanf() and scan sets:

const char* s = "ab234cid*(s349*(20kd";
int i1, i2, i3;
if (3 == sscanf(s,
                "%*[^0123456789]%d%*[^0123456789]%d%*[^0123456789]%d",
                &i1,
                &i2,
                &i3))
{
    printf("%d %d %d\n", i1, i2, i3);
}

where %*[^0123456789] means ignore input until a digit is found. See demo at http://ideone.com/2hB4UW .

Or, if the number of numbers is unknown you can use %n specifier to record the last position read in the buffer:

const char* s = "ab234cid*(s349*(20kd";
int total_n = 0;
int n;
int i;
while (1 == sscanf(s + total_n, "%*[^0123456789]%d%n", &i, &n))
{
    total_n += n;
    printf("%d\n", i);
}
like image 21
hmjd Avatar answered Oct 24 '22 20:10

hmjd