rot13第二种实现

  1. pub fn another_rot13(text: &str) -> String {
  2. let input = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  3. let output = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";
  4. text.chars()
  5. .map(|c| match input.find(c) {
  6. Some(i) => output.chars().nth(i).unwrap(),
  7. None => c,
  8. })
  9. .collect()
  10. }
  11. #[cfg(test)]
  12. mod tests {
  13. // Note this useful idiom: importing names from outer (for mod tests) scope.
  14. use super::*;
  15. #[test]
  16. fn test_simple() {
  17. assert_eq!(another_rot13("ABCzyx"), "NOPmlk");
  18. }
  19. #[test]
  20. fn test_every_alphabet_with_space() {
  21. assert_eq!(
  22. another_rot13("The quick brown fox jumps over the lazy dog"),
  23. "Gur dhvpx oebja sbk whzcf bire gur ynml qbt"
  24. );
  25. }
  26. #[test]
  27. fn test_non_alphabet() {
  28. assert_eq!(another_rot13("🎃 Jack-o'-lantern"), "🎃 Wnpx-b'-ynagrea");
  29. }
  30. }