Does anyone have an idea if this can be done smarter, better, faster?
check out: strtok() ... this breaks a string into tokens at each of one or more delimiters.
use it to break the string at each '+' or '-' (the delimiters), then check if the first one or more characters of each resulting string (the tokens) are numerals.
if it does, then push that number onto your result array. if it doesn't, skip on to the next token.
.
jephthah
Posting Maven
2,587 posts since Feb 2008
Reputation Points: 2,143
Solved Threads: 179
untested but here...
int main()
{
char tmp_array[100];
const char* seq = "+1236,,..,,actgn+3ACT-4CCCC";
printf("%s\n",seq);
while (*seq)
{ // pre-scan for +-
if (*seq != '-' && *seq != '+')
{
seq++;
continue;
}
char *p = tmparray;
*p++ = *seq++;
while (*seq)
{
if ((*seq < '0') || ('9' < *seq))
{
break;
}
*p++ = *seq++;
}
*p = 0;
printf("numbers in substrings are: %d\n",atoi(tmp_array));
}
return 0;
}
wildgoose
Practically a Posting Shark
896 posts since Jun 2009
Reputation Points: 546
Solved Threads: 99
But if allowed to use off the shelf library functions, then poster jephthah has the right idea!
wildgoose
Practically a Posting Shark
896 posts since Jun 2009
Reputation Points: 546
Solved Threads: 99
Double the processing time. No optimal!
Why process a list twice when you can do it once!
wildgoose
Practically a Posting Shark
896 posts since Jun 2009
Reputation Points: 546
Solved Threads: 99
wildgoose: posting "Untested" code on daniweb's C forum is generally risky business :P
anyhow, being able to use strtok() correctly is tricky for a new user. Also make sure you understand what is going on with strtol()
char string[100]="+1236,,..,,actgn+3ACT-4CCCC";
char *token, *ptr;
int value;
token = strtok(string,"+-");
printf ("found numbers: ");
while (token != NULL)
{
value = strtol(token,&ptr,10);
if (ptr != token)
printf(" %d,",value);
token = strtok(NULL,"+-");
}
printf("\n");
.
jephthah
Posting Maven
2,587 posts since Feb 2008
Reputation Points: 2,143
Solved Threads: 179
well, that's a nice bit of feature creep to throw out there at the last minute.
do you work in marketing?
jephthah
Posting Maven
2,587 posts since Feb 2008
Reputation Points: 2,143
Solved Threads: 179