Circular shift a cstring in C++

Hi, I need to circular right shift a cstring in C++

Let's say I have unsigned char test[10] = "HELLO!!!\0"; How would I go about circularly shifting this to the right? Inline assembly instructions would be ok too

Thanks for the help
I would copy the string into a deque<char> and then use deque::push_back() and pop_front() or push_front() and pop_back() to move letters from the front to the back or vice versa
1
2
3
4
5
6
7
8
9
#include <algorithm>

int main()
{
    char test[] = "The string to be rotated." ;

    // circular right shift 'test' by 6
    std::rotate( test, test+6, test+sizeof(test)-1 ) ;
}
wish i'd known that existed... ;)
If you are not allowed to use standard algorithms then you can write the function yourself. It is simple if you need to shift a string to the right by one character.

1
2
3
4
5
6
7
8
9
10
11
12
13
char * string_rotate_right( char *s )
{
   size_t n = strlen( s );

   if ( n > 1 )
   {
      char c = s[n - 1];
      memmove( s + 1, s, n - 1 );
      *s = c;
   }

   return ( s );
}

Last edited on
Thanks for the tips, but...

I need to shift the entire array by bits, not characters. Every bit shifted out of a cell in an array goes to the next cell, the last bit of the last cell gets rotated back into the beginning of the first cell of the array.
> I need to shift the entire array by bits, not characters.

So don't use a string.
Use std::bitset<> if the number of bits is known at compile time;
boost::dynamic_bitset<> otherwise.
Topic archived. No new replies allowed.