The problem
The quantity has been combined up with the textual content. Your aim is to retrieve the quantity from the textual content, can you come back the quantity again to its unique state?
Activity
Your activity is to return a quantity from a string.
Particulars
You can be given a string of numbers and letters combined up, you need to return all of the numbers in that string within the order they happen.
The answer in C
Possibility 1:
lengthy lengthy filter_string(const char *s) {
lengthy lengthy n=0;
char c;
whereas( (c=*s++) ){
if ( c>='0' && c<='9' ) n = 10*n + c-'0';
}
return n;
}
Possibility 2:
#embrace <ctype.h>
lengthy lengthy filter_string(const char *worth) {
lengthy lengthy ret = 0;
for (const char *p = worth; *p; p++) {
if (isdigit(*p)) ret = ret * 10 + *p - '0';
}
return ret;
}
Possibility 3:
#embrace <ctype.h>
#embrace <string.h>
#embrace <stdlib.h>
#embrace <stdio.h>
lengthy lengthy filter_string(const char *worth) {
lengthy lengthy l = 0;
char* ptr;
char* s = calloc(strlen(worth) + 1, 1);
char* r = s;
whereas(*worth) {
if(isdigit(*worth)) *s++ = *worth;
worth++;
}
l = strtol(r, &ptr, 10);
return l;
}
Take a look at circumstances to validate our resolution
#embrace <criterion/criterion.h>
#embrace <stdio.h>
#embrace <stdlib.h>
#embrace <time.h>
void do_test(const char *worth, lengthy anticipated);
Take a look at(solution_test, fixed_tests)
{
do_test("123", 123);
do_test("a1b2c3", 123);
do_test("aa1bb2cc3dd", 123);
}
Take a look at(solution_test, random_tests)
{
srand(time(NULL));
#outline randomLetter() (rand() % 26 + 'a')
#outline randomValue() (llabs(((lengthy lengthy)rand() << 32) + rand()))
for (int trial = 1; trial <= 50; trial++)
{
lengthy lengthy anticipated = randomValue();
char num[20], worth[500] = {0};
sprintf(num, "%lld", anticipated);
for (int i = 0, j = 0; num[i]; i++)
{
for (int okay = rand() % 5 + 1; okay; k--)
worth[j++] = randomLetter();
worth[j++] = num[i];
for (int okay = rand() % 5 + 1; okay; k--)
worth[j++] = randomLetter();
}
do_test(worth, anticipated);
}
}