Extract Number from Char* Array (C-String)

2019-07-20 06:30发布

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

标签: c string parsing
6条回答
2楼-- · 2019-07-20 06:37

Quick and dirty:

char* string = ".word 40";
char number[5];
unsigned int length = strlen(string);
strcpy(number, string + length - 2);
查看更多
ら.Afraid
3楼-- · 2019-07-20 06:41
int foo;
scanf("%*s %d", &foo);

The asterisk tells scanf not to store the string it reads. Use fscanf if you're reading from a file, or sscanf if the input is already in a buffer.

查看更多
闹够了就滚
4楼-- · 2019-07-20 06:48

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.

查看更多
劳资没心,怎么记你
5楼-- · 2019-07-20 06:48
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.

查看更多
Ridiculous、
6楼-- · 2019-07-20 06:50

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.

查看更多
7楼-- · 2019-07-20 06:52

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)

查看更多
登录 后发表回答