Circular shift a cstring in C++

Jan 29, 2013 at 9:26am
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
Jan 29, 2013 at 9:30am
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
Jan 29, 2013 at 9:55am
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 ) ;
}
Jan 29, 2013 at 10:01am
wish i'd known that existed... ;)
Jan 29, 2013 at 12:22pm
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 Jan 29, 2013 at 12:22pm
Jan 30, 2013 at 7:26am
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.
Jan 30, 2013 at 7:36am
> 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.