1pub fn str_rev(s: &str) -> String {
14 s.chars().rev().collect::<String>()
15}
16
17pub fn is_palindrome(s: &str) -> bool {
29 s == str_rev(s)
30}
31
32pub fn chomp(text: &mut String) {
51 if text.ends_with('\n') {
52 text.pop();
53 if text.ends_with('\r') {
54 text.pop();
55 }
56 }
57}
58
59pub fn center(s: &str, width: usize) -> String {
74 format!("{s:^w$}", w = width)
75}
76
77pub fn capitalize(s: &str) -> String {
93 if s.is_empty() {
94 String::new()
95 } else {
96 let chars: Vec<char> = s.chars().collect();
97 let first = chars[0].to_uppercase();
98 let rest = chars.into_iter().skip(1).collect::<String>().to_lowercase();
99 format!("{}{}", first, rest)
100 }
101}
102
103#[cfg(test)]
106mod tests {
107 use super::*;
108
109 #[test]
110 fn str_rev_test1() {
111 assert_eq!(str_rev(""), "");
112 assert_eq!(str_rev("a"), "a");
113 assert_eq!(str_rev("ab"), "ba");
114 assert_eq!(str_rev("anna"), "anna");
115 assert_eq!(str_rev("abc"), "cba");
116 assert_eq!(str_rev("AbCdE"), "EdCbA");
117 }
118
119 #[test]
120 fn is_palindrome_test1() {
121 assert!(is_palindrome(""));
122 assert!(is_palindrome("a"));
123 assert!(is_palindrome("aa"));
124 assert!(is_palindrome("anna"));
125 assert!(is_palindrome("görög"));
126 }
127
128 #[test]
129 fn is_palindrome_test2() {
130 assert_eq!(is_palindrome("ab"), false);
131 assert_eq!(is_palindrome("Anna"), false);
132 }
133
134 #[test]
135 fn chomp_test1() {
136 let mut text = "".to_string();
137 chomp(&mut text);
138 assert_eq!(text, "");
139 let mut text = "abc".to_string();
141 chomp(&mut text);
142 assert_eq!(text, "abc");
143 let mut text = "\n".to_string();
145 chomp(&mut text);
146 assert_eq!(text, "");
147 let mut text = "\r\n".to_string();
149 chomp(&mut text);
150 assert_eq!(text, "");
151 let mut text = "\nend".to_string();
153 chomp(&mut text);
154 assert_eq!(text, "\nend");
155 let mut text = "\r\nend".to_string();
157 chomp(&mut text);
158 assert_eq!(text, "\r\nend");
159 let mut text = "longer\nstring\n".to_string();
161 chomp(&mut text);
162 assert_eq!(text, "longer\nstring");
163 }
164
165 #[test]
166 fn center_test1() {
167 assert_eq!(center("-", 0), "-");
168 assert_eq!(center("-", 1), "-");
169 assert_eq!(center("-", 2), "- ");
170 assert_eq!(center("-", 3), " - ");
171 }
172
173 #[test]
174 fn capitalize_test1() {
175 assert_eq!(capitalize(""), "");
176 assert_eq!(capitalize("a"), "A");
177 assert_eq!(capitalize("aa"), "Aa");
178 assert_eq!(capitalize("aNnA"), "Anna");
179 }
180}