Home
Rust
ROT13 Function
Updated Jan 13, 2022
Dot Net Perls
ROT13. Imagine the most powerful encryption algorithm possible. The ROT13 function is not that algorithm. Instead ROT13 simply shifts characters based on their values.
With some ifs, we can implement ROT13 in Rust. We can allocate a new string, with a capacity, and append to it with push(). We can act upon the bytes of the string.
Example program. To begin, we add the rot13 function which receives a String, and returns a String. We loop over the bytes of the string.
Loop, String Chars
Info To speed up the function, we use the with capacity function to avoid resizes of the String we return.
Detail To adjust the byte to its rotated value, we introduce a mutable local. Then we cast the adjusted value to a char.
Result We can see the rot13 function round-trips ASCII data correctly—the "omicron" string is returned after rot13 is called twice.
fn rot13(data: String) -> String { // Create new string. let mut result = String::with_capacity(data.len()); // Loop over bytes. for c in data.bytes() { // Adjust the byte. let mut adjusted = c; if c >= b'a' && c <= b'z' { if c > b'm' { adjusted -= 13; } else { adjusted += 13; } } else if c >= b'A' && c <= b'Z' { if c > b'M' { adjusted -= 13; } else { adjusted += 13; } } // Push to new string. result.push(adjusted as char); } result } fn main() { println!("{}", rot13("omicron".to_string())); println!("{}", rot13(rot13("omicron".to_string()))); println!("{}", rot13("The apartment is 700 square feet.".to_string())); }
bzvpeba omicron Gur ncnegzrag vf 700 fdhner srrg.
Some issues. Because we get the bytes from the string, this function will not work well on non-ASCII text. It could be fixed by calling chars() in the for-loop.
for
A summary. The ROT13 function has little practical use except in programming tutorials. The logic here can be used to translate strings in an iterative way.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 13, 2022 (new).
Home
Changes
© 2007-2025 Sam Allen