| 1 | #![cfg(test)] |
| 2 | /// Return true iff `s` contains exactly one occurrence of substring `t`. |
| 3 | pub fn contains_once(s: &str, t: &str) -> bool { |
| 4 | match (s.find(t), s.rfind(t)) { |
| 5 | (Some(i), Some(j)) => i == j, |
| 6 | _ => false, |
| 7 | } |
| 8 | } |
| 9 | |
| 10 | #[allow(dead_code)] |
| 11 | pub fn print_with_line_numbers(s: &str) { |
| 12 | for (i, t) in s.lines().enumerate() { |
| 13 | println!("{:>2}│ {}", i + 1, t); |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | #[cfg(test)] |
| 18 | mod tests { |
| 19 | use crate::tests::test_utils::*; |
| 20 | |
| 21 | #[test] |
| 22 | fn test_contains_once_1() { |
| 23 | assert!(contains_once("", "")); |
| 24 | } |
| 25 | |
| 26 | #[test] |
| 27 | fn test_contains_once_2() { |
| 28 | assert!(contains_once("a", "a")); |
| 29 | } |
| 30 | |
| 31 | #[test] |
| 32 | fn test_contains_once_3() { |
| 33 | assert!(!contains_once("", "a")); |
| 34 | } |
| 35 | |
| 36 | #[test] |
| 37 | fn test_contains_once_4() { |
| 38 | assert!(!contains_once("a", "b")); |
| 39 | } |
| 40 | |
| 41 | #[test] |
| 42 | fn test_contains_once_5() { |
| 43 | assert!(!contains_once("a a", "a")); |
| 44 | } |
| 45 | |
| 46 | #[test] |
| 47 | fn test_contains_once_6() { |
| 48 | assert!(contains_once("a b", "b")); |
| 49 | } |
| 50 | } |