Trying to modify a string >=(

closed account (365X92yv)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
string Cipher::key_rotate(string key) 
{
	char temp;
	char replace;
	int count = 0;
	for(int i=0;i<key.length();i++)
	{
		count++;
	}
	cout << count << endl;

	//Does the shifting of the key.	
	for(int i=0;i<count;i++)
	{
		temp = key.at( i ); //takes the iTH spot in the key and stores it into a char variable.
		replace = key.at(i+1); //
		key.append(1, temp);
	}

	//testing if the new key has been shifted.
	for(int i=0;i<key.length();i++)
	{
		cout << key.at( i );
	}

	return key;
}

What I want this function to do is take the key, which for the sake of this is
 
string key = "defghijklmnopqrstuvwxyzabc";

I would like to use the function above that I wrote to take whatever is at the iTH spot of the key and store it in a temp variable. Then take everything in the string and move it up one spot. So it would take the string:

string key = "defghijklmnopqrstuvwxyzabc";

And make it into:

string key = "efghijklmnopqrstuvwxyzabcd";

And keep moving everything from the front to the back. The problem I keep coming across is that it just makes the key string longer and just flubs up the whole thing. I've tried a few things to help it to not infinitely change string and so now I use count so it just runs as long as the key string is. I still get something stupid like:

string key = "efghijklmnopqrstuvwxyzabcdefghij......

Anyways, some help would be nice to see what's going on with my code.
Last edited on
Hmm, I don't know if there is some standard way to do this, but how I would do it is so
1. Copy string minus element 0 into a temp string
2. Take element 0 and append it to temp string
3. Replace main string with temp string
4. Rinse and repeat
Unless your intent is to learn how to implement a rotate algorithm, use std::rotate()
http://cplusplus.com/reference/algorithm/rotate/

1
2
3
4
5
std::string rotate_by( std::string str, std::string::size_type n = 1 )
{
    std::rotate( str.begin(), str.begin() + n%str.size(), str.end() ) ;
    return str ;
}

Topic archived. No new replies allowed.