How to rotate a string left and right by N chars in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void rotate(char *s, int n) {
    char *tmp = strdup(s);
    int len = strlen(s);
 
    if (n < 0)
        n = len + (n % len);
    for (int i = 0; s[i] != 0; i++) {
        int idx = (i + n) % len;
        tmp[idx] = s[i];
    }
    memcpy(s, tmp, len);
    free(tmp);
}
 
int main(void) {
    char s1[] = "aabcccdeeffffgac"; 
 
	puts(s1);
    rotate(s1, -3); // left
    puts(s1);
 
    char s2[] = "aabcccdeeffffgac"; 
 
	puts("\n");
	puts(s2);
    rotate(s2, 7); // right
    puts(s2);
 
 
    return 0;
}
   
   
   
/*
run:
   
aabcccdeeffffgac
cccdeeffffgacaab


aabcccdeeffffgac
ffffgacaabcccdee
   
*/

 



answered Jun 19, 2020 by avibootz
edited Jun 19, 2020 by avibootz

Related questions

1 answer 78 views
78 views asked Nov 28, 2023 by avibootz
2 answers 108 views
1 answer 150 views
2 answers 91 views
1 answer 143 views
1 answer 80 views
...