Thursday, March 2, 2023
HomeSoftware EngineeringThe best way to Filter a Quantity in C

The best way to Filter a Quantity in C


The problem

The quantity has been blended up with the textual content. Your objective is to retrieve the quantity from the textual content, can you come the quantity again to its authentic state?

Job

Your activity is to return a quantity from a string.

Particulars

You may be given a string of numbers and letters blended up, it’s a must 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;
}

Check circumstances to validate our answer

#embrace <criterion/criterion.h>
#embrace <stdio.h>
#embrace <stdlib.h>
#embrace <time.h>

void do_test(const char *worth, lengthy anticipated);

Check(solution_test, fixed_tests)
{
    do_test("123", 123);
    do_test("a1b2c3", 123);
    do_test("aa1bb2cc3dd", 123);
}
Check(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);
    }
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments