| Chih-Hung Hsieh | cfc3a23 | 2020-06-10 20:13:05 -0700 | [diff] [blame] | 1 | pub fn remove_to<'s>(s: &'s str, c: char) -> &'s str { |
| 2 | match s.rfind(c) { |
| 3 | Some(pos) => &s[(pos + 1)..], |
| 4 | None => s, |
| 5 | } |
| 6 | } |
| 7 | |
| 8 | pub fn remove_suffix<'s>(s: &'s str, suffix: &str) -> &'s str { |
| 9 | if !s.ends_with(suffix) { |
| 10 | s |
| 11 | } else { |
| 12 | &s[..(s.len() - suffix.len())] |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | #[cfg(test)] |
| 17 | mod test { |
| 18 | |
| 19 | use super::remove_suffix; |
| 20 | use super::remove_to; |
| 21 | |
| 22 | #[test] |
| 23 | fn test_remove_to() { |
| 24 | assert_eq!("aaa", remove_to("aaa", '.')); |
| 25 | assert_eq!("bbb", remove_to("aaa.bbb", '.')); |
| 26 | assert_eq!("ccc", remove_to("aaa.bbb.ccc", '.')); |
| 27 | } |
| 28 | |
| 29 | #[test] |
| 30 | fn test_remove_suffix() { |
| 31 | assert_eq!("bbb", remove_suffix("bbbaaa", "aaa")); |
| 32 | assert_eq!("aaa", remove_suffix("aaa", "bbb")); |
| 33 | } |
| 34 | } |