The right way to Filter out a Quantity in C

The problem

The quantity has been blended up with the textual content. Your purpose is to retrieve the quantity from the textual content, are you able to go back the quantity again to its authentic state?

Activity

Your activity is to go back a bunch from a string.

Main points

You are going to be given a string of numbers and letters blended up, you must go back the entire numbers in that string within the order they happen.

The answer in C

Choice 1:

lengthy lengthy filter_string(const char *s) {
  lengthy lengthy n=0;
  char c;
  whilst( (c=*s++) ){
    if ( c>='0' && c<='9' ) n = 10*n + c-'0';
  }
  go back n;
}

Choice 2:

#come with <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';
  }      

  go back ret;
}

Choice 3:

#come with <ctype.h>
#come with <string.h>
#come with <stdlib.h>
#come with <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;
   whilst(*worth) {
     if(isdigit(*worth)) *s++ = *worth;      
     worth++;    
   }
  l = strtol(r, &ptr, 10);   
  go back l;
}

Check circumstances to validate our answer

#come with <criterion/criterion.h>
#come with <stdio.h>
#come with <stdlib.h>
#come with <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 ok = rand() % 5 + 1; ok; k--)
                worth[j++] = randomLetter();
            worth[j++] = num[i];
            for (int ok = rand() % 5 + 1; ok; k--)
                worth[j++] = randomLetter();
        }
        do_test(worth, anticipated);
    }
}

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: