Hello, it's my first question on the forum! Now, I have a certain method of encrypting text. You get the first character of the word. For example in the word "hacker", you get 'h', and then you get the last character 'r'. The encrypted word until now is "hr". Then we get the same word with the 'h' and 'r' removed, now it's "acke". I do the same thing and get the first character 'a' and the last one 'e' and them to the encrypted word: it is now "hrae". The left letters of the word are "ck", again we do the same thing and take the first character 'c' and the last character 'k' and and add them to the new encrypted word so it is "hraeck". Please keep in mind that the above word has an even number of characters and at the end had 2 characters left 'c' and 'k',first and last, in some cases of words with an odd number of characters, only one character is left! I'm completely lost on how to encrypt and decrypt this. ANY help or guidance is much appreciated.
Thanks,
OvO (looks like a face with eyes and a nose, huh?)
#include <iostream>
#include <string>
std::string encrypt(const std::string& word)
{
std::string result;
if (word.size()) // sanity check for empty string
{
std::size_t i = 0; // index of leftmost character
std::size_t j = word.size() - 1; // index of rightmost character
while (i < j)
{
result += word[i++]; // You get the first character of the word
result += word[j--]; // and then you get the last character
}
if (i == j) // in some cases of words with an odd number of characters, only one character is left!
result += word[i];
}
return result;
}
int main()
{
std::cout << encrypt("hacker") << '\n'; // even number of characters.
std::cout << encrypt("phone") << '\n'; // odd number of characters.
}
What about processing a whole string? Is there a way to do that without processing each word alone?
1 2 3 4 5
#include <iostream>
int main()
{
std::cout<<"Thanks for your answer!";
}
By the way, is it allowed in these forums to just add another part in the topic just to thank the one who answered me? I have always used Stack Overflow, so I don't know. You deserve the thank you, I beleive ;)
Is there a way to do that without processing each word alone?
Sure. Just treat a string containing a sentence the same as you would a "word." It is, perhaps, an unfortunate choice of name for the parameter encrypt takes. text might serve.