Pheegy
Pheegy

Reputation: 37

Removing the leading zeroes of a number stored in string

struct number {char digits[11];};

The following method removes leading zeroes from (*a).digits

void remove_zero(struct number *a); 

Example: (*a).digits 000013204 ---> 13204

My approach is to define a variable b equals to (*a).digits, start seaching for the first non-zero number in b, then replace (*a).digits with the rest of b. However, I am having trouble implementing the code

void remove_zero(struct number *a) {
char b = (*a).digits;
while (b){   // <--- (b) indicates that it hasnt reached the terminator,right?
  if (b != '0')
    { //<-- here is where to replace (*a).digits with the rest of b, but how to?
break;
    }
  }
}

Upvotes: 0

Views: 125

Answers (2)

mhawke
mhawke

Reputation: 87064

In general it's clearer to deference a pointer to a struct and access its attributes using the -> operator, e.g. rather than

char b = (*a).digits;

do this

char *b = a->digits;

Note that digits is an array of chars, so b needs to be an array of chars, or a pointer to a char as shown here.

So:

void remove_zero(struct number *a)
{
    char *b = a->digits;
    char *end = a->digits + sizeof a->digits - 1;

    while (b < end && *b == '0')
        b++;

    if (b != a->digits)
    {
        size_t n = end - b;
        memmove(a->digits, b, n);
        a->digits[n] = '\0';
    }
}

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409166

So you have an array that contains e.g.

+---+---+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 1 | 3 | 2 | 0 | 4 | \0|   |
+---+---+---+---+---+---+---+---+---+---+---+

And you want it to contain

+---+---+---+---+---+---+---+---+---+---+---+
| 1 | 3 | 2 | 0 | 4 | \0|   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+---+

From the "images" above, it should be pretty clear that this can be done using a simple movement of the data.

So one solution is to find the first non-zero character, and move from that to the beginning of the array.

Upvotes: 5

Related Questions