Reputation: 21069
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
Upvotes: 2
Views: 24777
Reputation: 565
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.
Upvotes: 1
Reputation: 206646
You can use strtok() to extract the two strings with space as an delimiter.
#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.
Upvotes: 8
Reputation: 25874
Quick and dirty:
char* string = ".word 40";
char number[5];
unsigned int length = strlen(string);
strcpy(number, string + length - 2);
Upvotes: 0
Reputation: 6846
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.
Upvotes: 0
Reputation: 1534
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.
Upvotes: 1