- Given a string of length , shift each character of the string by positions to the right, where .
For example: Say =
Shifting each character in by positions to the right would result into .
Note that i.e. 'h' is moved by 2 positions to the . Also, i.e. 'r', which is the last character in comes round-about back to as there is no space for 'r' to go beyond the limits of string length.
"hacker"
and . Here .Shifting each character in by positions to the right would result into .
Note that i.e. 'h' is moved by 2 positions to the . Also, i.e. 'r', which is the last character in comes round-about back to as there is no space for 'r' to go beyond the limits of string length.
Approach:
- Declare another auxillary string that is of the same size as .
- Copy element of to the position in . This means, where .
- Make sure that never exceeds , because that will try to access a memory location which is not declared in . There's a simple trick to ensure that - use .
#include <iostream>
#include<string>
using namespace std;
int main()
{
string s,p;
cin>>s;
int k;
cin>>k;
for(int i=0;i<s.size();i++)
{
int index=(i+k)%s.size();
p[index]=s[i];
}
for(int i=0;i<s.size();i++) { cout<<p[i];}
No comments:
Post a Comment