0

I am new to C, and I am learning shift operation.

I understand the shift operation if the data is a binary number, but for my code in this case, I want to implement the case that 't', 'h', 'i', 's', ' ', '\0' are all discarded or shifted, and move 'a' to the first element of this string.

Can I do this behavior by using shift operator? If so, why is so?

Really appreciated.

char words[10] = {'t', 'h', 'i', 's', ' ', '\0', 'a', 'b', 'c'};
DigitalSoul
  • 139
  • 1
  • 8

1 Answers1

1

The shift operator you are talking about is basically bitwise operator. You can't use this to shift array of characters.

To accomplish what you asked, you can write a function. Suppose you want left shift -

int leftShift(char *words, int len)
{
    int i;
    for(i = 1; i < len; i++)
    {
        words[i - 1] = words[i];
    }
    len--;
    return len;
}

What this function does? - it takes an array and length of that array as parameter, and perform left shift one time.

So then from your main function you can just call this method any number of times you want -

int main(void) {

    char words[10] = {'t', 'h', 'i', 's', ' ', '\0', 'a', 'b', 'c'};
    int len = 10;

    len = leftShift(words, len); // left shift one time - this will discard 't'
    len = leftShift(words, len); // left shift one time - this will discard 'h'

   //finally print upto len, because len variable holds the new length after discarding two characters.
    int i;
    for(i = 0; i < len; i++)
    {
        printf("'%c', ", words[i]);
    }

    return 0;
}

This is very trivial idea, surely this approach can be improved in many ways. But I think you got the basic idea.

Arnab Roy
  • 619
  • 5
  • 16