Haibo Huang | ba676d3 | 2020-08-12 13:52:13 -0700 | [diff] [blame] | 1 | pub fn remove_to<'s, P>(s: &'s str, pattern: P) -> &'s str |
| 2 | where |
| 3 | P: Fn(char) -> bool, |
| 4 | { |
| 5 | match s.rfind(pattern) { |
Chih-Hung Hsieh | 92ff605 | 2020-06-10 20:18:39 -0700 | [diff] [blame] | 6 | Some(pos) => &s[(pos + 1)..], |
| 7 | None => s, |
| 8 | } |
| 9 | } |
| 10 | |
| 11 | pub fn remove_suffix<'s>(s: &'s str, suffix: &str) -> &'s str { |
| 12 | if !s.ends_with(suffix) { |
| 13 | s |
| 14 | } else { |
| 15 | &s[..(s.len() - suffix.len())] |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | pub fn capitalize(s: &str) -> String { |
| 20 | if s.is_empty() { |
| 21 | return String::new(); |
| 22 | } |
| 23 | let mut char_indices = s.char_indices(); |
| 24 | char_indices.next().unwrap(); |
| 25 | match char_indices.next() { |
| 26 | None => s.to_uppercase(), |
| 27 | Some((i, _)) => s[..i].to_uppercase() + &s[i..], |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | #[cfg(test)] |
| 32 | mod test { |
| 33 | |
| 34 | use super::capitalize; |
| 35 | use super::remove_suffix; |
| 36 | use super::remove_to; |
| 37 | |
| 38 | #[test] |
| 39 | fn test_remove_to() { |
Haibo Huang | ba676d3 | 2020-08-12 13:52:13 -0700 | [diff] [blame] | 40 | assert_eq!("aaa", remove_to("aaa", |c| c == '.')); |
| 41 | assert_eq!("bbb", remove_to("aaa.bbb", |c| c == '.')); |
| 42 | assert_eq!("ccc", remove_to("aaa.bbb.ccc", |c| c == '.')); |
Chih-Hung Hsieh | 92ff605 | 2020-06-10 20:18:39 -0700 | [diff] [blame] | 43 | } |
| 44 | |
| 45 | #[test] |
| 46 | fn test_remove_suffix() { |
| 47 | assert_eq!("bbb", remove_suffix("bbbaaa", "aaa")); |
| 48 | assert_eq!("aaa", remove_suffix("aaa", "bbb")); |
| 49 | } |
| 50 | |
| 51 | #[test] |
| 52 | fn test_capitalize() { |
| 53 | assert_eq!("", capitalize("")); |
| 54 | assert_eq!("F", capitalize("f")); |
| 55 | assert_eq!("Foo", capitalize("foo")); |
| 56 | } |
| 57 | } |