1

For example, if I have a string in an char array like "abcdef", then I would like to print a new string "bcdefa" then next would be "cdefab" and so on until it cycles through the string ending up at "fabcde"

Sorry I am new to C and not the best of array manipulation and unsure what would be the easiest approach.

I was thinking maybe rearranging the indexes at first? but I wasn't sure how to loop that. Or could I approach this in a more efficient way using some function from the string.h library?

Hispazn
  • 103
  • 3
  • 10

2 Answers2

5

This is called array rotation, and there's a nice trick for that. You reverse both parts, and then you reverse the whole thing. Here's an example:

#include  <stdio.h>
#include <string.h>

void swap(char* a, char* b) {
    char tmp = *a;
    *a = *b;
    *b = tmp;
}

void rev(char* array, size_t n) {
    for (size_t i = 0; i < n / 2; i++)
        swap(array + i, array +(n - i - 1));
}

void rotate_one(char* str) {
    rev(str + 1, strlen(str) - 1);
    rev(str, strlen(str));
}

See Demo

Yam Marcovic
  • 7,953
  • 1
  • 28
  • 38
  • Very nice, but doing his homework for him probably doesn't help him out in the long run. Not my downvote, incidentally. – mah Feb 23 '16 at 17:11
  • ohh i see, and it is just a sub problem for my main problem. I need to apply the similar concept to a bigger scale with more restrictions but i figured if i could see it with no restrictions I could reapply in a way I need it. – Hispazn Feb 23 '16 at 17:14
2

This is the string:

char str[] = "abcdef";

Save the first character, because it will be overwritten later:

char tmp = str[0];

Then move the rest of the string one character forward. Please not that strcpy() is not allowed here, because on overlapped strings the behaviour is undefinded.

memmove(str, &(str[1]), strlen(&(str[1])));

Then store the saved first character at the end:

str[strlen(str) - 1] = tmp;

And one rotation is done. And

printf("%s\n", str);

will show bcdefa.

kwarnke
  • 1,424
  • 1
  • 15
  • 10