Develop an ROT13 algorithm and optimize it. You need to change the individual characters in a string based on logic. As an example, implement the ROT13 cipher to perform character transformations.
| Input | ROT13 output |
|
There was once a fox who had a pretty fur coat. |
Gurer jnf bapr n sbk jub unq n cerggl she pbng. |
|
Gurer jnf bapr n sbk jub unq n cerggl she pbng. |
There was once a fox who had a pretty fur coat. |
ROT13 rotates each character in text by 13 places. The method is a primitive cipher similar to the one used by Julius Caeser, dictator of the Roman Republic, as the Caesar Cipher. Here's one implementation, but it is slow.
static string RotateA(string value)
{
//
// Version of Rotate that uses StringBuilder.
//
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.Length; i++)
{
int t = (int)value[i];
if (t >= 65 && t < 91)
{
t += 13;
if (t >= 91)
{
t -= 26;
}
}
else if (t >= 97 && t < 123)
{
t += 13;
if (t >= 123)
{
t -= 26;
}
}
b.Append((char)t);
}
return b.ToString();
}
We can do much better than the method above and use the ToCharArray method. We convert the string into a char array and modify it in-place. This version is faster because it uses ToCharArray.
static string RotateB(string value)
{
//
// Modifies the characters in-place using ToCharArray.
//
char[] c = value.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
int t = (int)c[i];
if (t >= 65 && t < 91)
{
t += 13;
if (t >= 91)
{
t -= 26;
}
}
else if (t >= 97 && t < 123)
{
t += 13;
if (t >= 123)
{
t -= 26;
}
}
c[i] = (char)t;
}
return new string(c);
}
They are both fast, but the version using ToCharArray is much faster. Here's a graph and a table comparing the two Rotate methods being run many times.
| Name | Description | Time in ms |
| RotateB | Uses ToCharArray in-place. | 1388 |
| RotateA | Uses StringBuilder and copies. | 3604 |
The method here highlights the benefits of ToCharArray when it is used properly. ToCharArray can help a lot with other kinds of character manipulation, which I show in an article about uppercasing first letters in strings.