Question

Firstly I'd like to apologize for the bad titling, I'm not sure how to summarize this.

I'm creating a simple cipher program that uses a key that repeats to fit the plaintext length.

So if the key was "WATER" and the plaintext was "PRINGLE", the key would loop over like this; "WATERWA"

and I'm having trouble doing that. I'm not sure if it is difficult or if i am just having a massive brain fart but what i have so far just repeats the full string X times.

Can someone point me in the right direction?

Was it helpful?

Solution

You can do it in two steps:

  1. Repeat the first string by N (i.e. N = ceil(length(str2)/length(str1))) times.

  2. Get the sub-string of the long string of length that is equal to the second string.

Code example: http://ideone.com/pZrFx9

OTHER TIPS

string key2; //declare the string. It'll be the same length as plaintextString
for (i = 0; i < length(plaintextString); i++ {
    key2[i] = key1[i%(length(key1))]; //you may want to assign length(key1) to a variable
}

Like Jon said, you're definitely going to want to use the modulus operator here. This code is NOT syntactically checked but it should give you an idea as long as you're familiar with c++ syntax.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top