blob: e822bf8508db83dbb0090b0f679c4ca488fb2b6b [file] [log] [blame]
Chih-Hung Hsieh92ff6052020-06-10 20:18:39 -07001pub 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
8pub 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
16pub fn capitalize(s: &str) -> String {
17 if s.is_empty() {
18 return String::new();
19 }
20 let mut char_indices = s.char_indices();
21 char_indices.next().unwrap();
22 match char_indices.next() {
23 None => s.to_uppercase(),
24 Some((i, _)) => s[..i].to_uppercase() + &s[i..],
25 }
26}
27
28#[cfg(test)]
29mod test {
30
31 use super::capitalize;
32 use super::remove_suffix;
33 use super::remove_to;
34
35 #[test]
36 fn test_remove_to() {
37 assert_eq!("aaa", remove_to("aaa", '.'));
38 assert_eq!("bbb", remove_to("aaa.bbb", '.'));
39 assert_eq!("ccc", remove_to("aaa.bbb.ccc", '.'));
40 }
41
42 #[test]
43 fn test_remove_suffix() {
44 assert_eq!("bbb", remove_suffix("bbbaaa", "aaa"));
45 assert_eq!("aaa", remove_suffix("aaa", "bbb"));
46 }
47
48 #[test]
49 fn test_capitalize() {
50 assert_eq!("", capitalize(""));
51 assert_eq!("F", capitalize("f"));
52 assert_eq!("Foo", capitalize("foo"));
53 }
54}