# Parsing a string

• 11-04-2010
bhdavis1978
Parsing a string
Does anybody have any snippet of code they'd be willing to share to help me parse a number and a letter from a short string that looks like this 275a into 275 and a? There isn't an explicit limit on the number of digits that will exist in the number portion, it could range from 1 to 5 (e.g. 0 up to 99999). It seems that the way to do this would be using isdigit and isalpha.

Thanks,
• 11-04-2010
BillyTKid
Code:

if( 2==sscanf("275a","%d%c",&number,&letter) )
printf("\nnumber=%d letter=%c",number,letter);
else
puts("error on input");

• 11-04-2010
bhdavis1978
Okay, my brain is clearly fried.

Thanks BillyTKid.

What if the string is more complicated, something like

275g -> 34g 201q 202q 221s 266g 328m 334t

If there is any entry on a line, it will at least contain something like

275g ->

but then after that, there are an unknown number of entries, tab delimited, having the same format?
• 11-04-2010
bhdavis1978
nvm, figured it out with strtok. I think I just needed a break from the computer and some more sugar, caffeine and nicotine.

In case anyone is searching and finds this thread, this is how I did it

Code:

void parse_string(char string[], int *i, char *l)
// parses "numberchar" into two variables, one for the number, one for the character
// ty to BillyTKid
// e.g. converts 275a into 275 and a
{

int number;
char letter;

if (sscanf(string, "%d%c", &number, &letter)==2)
{
*i= number;
*l= letter;
}

else
puts("error on input");

}

void tokenize_string(char string[])
// takes in a string and tokenizes it, then passes off the individual tokens to parse_string
{

char *pch;
char character;
int number;

printf("Splitting string \"%s\" into tokens\n", string);
pch= strtok(string, "-");
while (pch!=NULL)
{
printf("%s\n", pch);
parse_string(pch, &number, &character);
printf("number is %d, character is %c\n", number, character);
pch=strtok(NULL, ">\t");
}

}

int main (int argc, const char * argv[]) {
// insert code here...

char str[]="275a -> 273b  13c";

tokenize_string(str);

return 0;
}