2

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

2
  • I believe this may be what you are seeking stackoverflow.com/questions/1031872/… Commented Oct 25, 2011 at 16:45
  • You should research to see if there exists a parser or lexer for the language you are interested in. Commented Oct 25, 2011 at 18:24

6 Answers 6

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Epic win to include the online demo!
3

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)

1 Comment

A code example would be nice, since it is stackoverflow.
1

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.

Comments

1
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.

Comments

0
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.

Comments

0

Quick and dirty:

char* string = ".word 40";
char number[5];
unsigned int length = strlen(string);
strcpy(number, string + length - 2);

2 Comments

That gets you the characters "40" but not an integer.
He didn't specify he wants an integer. He said "I would like to extract the integer part" but not in which format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.