How to rotate a given line left or right in C?

C function to rotate a string by a given number to the right or left. When a character rotates beyond the end or beginning of a line depending on the direction, it should wrap around

+3
source share
4 answers

given a string strwhose length lengthand number of revolutionsn

rotation to the left is equivalent

reverse(str, 0, n);
reverse(str, n, length);
reverse(str, 0, length);

turning right is equivalent

reverse(str, 0, length - n);
reverse(str, length - n, length);
reverse(str, 0, length);

Now you just need the inverse function.

Update: I was thinking about how you can use mod so that you always rotate in the right direction depending on the sign n.

eg.

int mod = n % length;
if (mod != 0) { //if 0, don't rotate
    reverse(str, 0, mod);
    reverse(str, mod, length);
    reverse(str, 0, length);
}

going through various occasions

if n == 5 and length = 10, mod = 5

n == 16 length = 10, mod = 6 - 16 = 6

n == 0 length = anything, mod = 0

n == -1 length = 10, mod = 9 - 1 , 9

n == -15 length = 9, mod = 3 - 15 , 3

+10

- :

void rot(char *buf, int len, int r)
{
  char *temp=malloc(r>=0?r:-r);
  if(r>=0)
  {
    memcpy(temp, buf+len-r, r);
    memmove(buf+r, buf, len-r);
    memcpy(buf, temp, r);
  }
  else
  {
    memcpy(temp, buf, r);
    memmove(buf, buf+r, len-r);
    memcpy(buf+len-r, temp, r);
  }

  free(temp);
}

, , r < len, len 1, , .

+2
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* strrot (int offset, size_t size, const char *inStr);

int main (int argc, const char * argv[]) {
    const char *rotStr = "rotateme";
    size_t rotStrSize = strlen(rotStr);
    char *resultStr;

    resultStr = strrot(-3, rotStrSize, rotStr);
    printf("-3, %s\n", resultStr);
    free(resultStr);

    resultStr = strrot(2, rotStrSize, rotStr);
    printf("+2, %s\n", resultStr);
    free(resultStr);

    resultStr = strrot(11, rotStrSize, rotStr);
    printf("+11, %s\n", resultStr);
    free(resultStr);

    resultStr = strrot(0, rotStrSize, rotStr);
    printf("0, %s\n", resultStr);
    free(resultStr);

    resultStr = strrot(-11, rotStrSize, rotStr);
    printf("-11, %s\n", resultStr);
    free(resultStr);

    return 0;
}

char* strrot (int offset, size_t size, const char *inStr) {
    char *result = (char *)malloc(size * sizeof(char));
    int trueOffset = size - (offset % size);

    int inIndex = trueOffset;
    int outIndex = 0;

    for (inIndex = trueOffset; inIndex < (int)size; inIndex++, outIndex++) {
        result[outIndex] = inStr[inIndex];
    }
    for (inIndex = 0; inIndex < trueOffset; inIndex++, outIndex++) {
        result[outIndex] = inStr[inIndex];
    }

    result[(int)size] = '\0';

    return result;
}

Results:

-3, atemerot
+2, merotate
+11, emerotat
0, rotateme
-11, atemerot
0
source

Source: https://habr.com/ru/post/1721954/


All Articles