Extract Number from Char* Array (C-String)

23,387

Solution 1

You can use sscanf to extract formated data from a string. (It works just like scanf, but reading the data from a string instead of from standard input)

Solution 2

You can use strtok() to extract the two strings with space as an delimiter.

Online Demo:

    #include <stdio.h>
    #include <string.h>

    int main ()
    {
        char str[] =".Word 40";
        char * pch;
        printf ("Splitting string \"%s\" into tokens:\n",str);
        pch = strtok (str," ");
        while (pch != NULL)
        {
            printf ("%s\n",pch);
            pch = strtok (NULL, " ");
        }
        return 0;
    }

Output:

Splitting string ".Word 40" into tokens:
.Word
40

If you want the number 40 as a numeric value rather than a string then you can further use atoi() to convert it to a numeric value.

Solution 3

char str[] = "A=17280, B=-5120. Summa(12150) > 0";
char *p = str;
do
{
if (isdigit(*p) || *p == "-" && isdigit(*(p+1)))
printf("%ld ", strtol(p,&p,0);
else
p++;
}while(*p!= '\0');

This code write in console all digits.

Solution 4

Check the string with

strncmp(".word ", (your string), 6);

If this returns 0, then your string starts with ".word " and you can then look at (your string) + 6 to get to the start of the number.

Share:
23,387
darksky
Author by

darksky

C, C++, Linux, x86, Python Low latency systems Also: iOS (Objective-C, Cocoa Touch), Ruby, Ruby on Rails, Django, Flask, JavaScript, Java, Bash.

Updated on October 26, 2020

Comments

  • darksky
    darksky over 3 years

    I have a string that occurs in this format:

    .word 40

    I would like to extract the integer part. The integer part is always different but the string always starts with .word. I have a tokenizer function which works on everything except for this. When I put .word (.word with a space) as a delimiter it returns null.

    How can I extract the number?

    Thanks

  • Carey Gregory
    Carey Gregory over 12 years
    That gets you the characters "40" but not an integer.
  • m0skit0
    m0skit0 over 12 years
    He didn't specify he wants an integer. He said "I would like to extract the integer part" but not in which format.
  • unwind
    unwind over 12 years
    Epic win to include the online demo!
  • Omar Tariq
    Omar Tariq over 8 years
    A code example would be nice, since it is stackoverflow.