Christian
Christian

Reputation: 593

Shifting a string of characters?

I'm writing a program that solves Caesar ciphers in C++. It takes a string of the alphabet and shifts it to the left each loop: "abc....yz" --> "bcd.....yza". The problem is after another loop it goes: "bcd.....yza" --> "cde.....yzaa".

char temp;       // holds the first character of string
string letters = "abcdefghijklmnopqrstuvwxyz";
while (true)
{
    temp = letters[0];
    for (int i = 0; i < 26; i++)
    {
        if (i == 25)
        {
            letters += temp;
        }
        letters[i] = letters[i + 1];
        cout << letters[i];
    }
    cin.get();
}

Copy and paste that code and you'll see what I'm talking about. How do I fix this mysterious problem?

Upvotes: 2

Views: 37791

Answers (3)

MSalters
MSalters

Reputation: 179779

If I'm not mistaken, your loop does precisely the same as the following code:

letters = letters.substr(1,25) + letters.substr(0,1);
//        [skip 1, take 25]    + [first char goes last]

Upvotes: 6

yasouser
yasouser

Reputation: 5177

You can achieve this easily using valarray< char >::cshift(n) (cyclical shift) method.

Upvotes: 3

Nemo
Nemo

Reputation: 71525

I think you need letters to be 27 characters, not 26, and instead of letters += temp (which grows the string every time), use letters[26] = temp[0].

...at which point you can just ditch temp entirely:

string letters = "abcdefghijklmnopqrstuvwxyz.";
while (true)
{
    letters[26] = letters[0];
    for (int i = 0; i < 26; i++)
    {

        letters[i] = letters[i + 1];
        cout << letters[i];
    }
    cin.get();
}

[edit]

Although the more natural way to handle this is to use arithmetic on the characters themselves. The expression 'a' + ((c - 'a' + n) % 26) will shift a char c by n places Caesar-style.

Upvotes: 4

Related Questions