-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstart_case.rs
52 lines (41 loc) · 1.44 KB
/
start_case.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//! Converts `String` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
//!
//! Example
//! ```
//! use lodash_rust::start_case;
//!
//! let value = String::from("--foo-bar--");
//! let res = start_case::new(&value);
//! println!("{res}") // "Foo Bar"
//! ```
extern crate regex;
pub fn new(s: &str) -> String {
let re = regex::Regex::new("[^a-zA-Z0-9]+").unwrap();
let result = re.replace_all(s, " ");
let result = result.trim();
let chars_list = result.chars().collect::<Vec<char>>();
let mut build_string = String::new();
let mut tmp = [0u8; 4];
for value in 0..chars_list.len() {
let mut current_char = chars_list[value];
// encode_utf8(&mut tmp)
if current_char.is_ascii_lowercase() && value == 0 {
current_char = current_char.to_ascii_uppercase();
}
if value > 0 && chars_list[value - 1] == ' ' {
current_char = current_char.to_ascii_uppercase();
}
if value > 0 && current_char.is_uppercase() && chars_list[value - 1].is_ascii_lowercase() {
build_string.push(' ');
current_char = current_char.to_ascii_uppercase();
}
build_string.push_str(current_char.encode_utf8(&mut tmp));
}
build_string
}
#[test]
fn test_new() {
assert_eq!(new("--foo-bar--"), "Foo Bar");
assert_eq!(new("fooBar"), "Foo Bar");
assert_eq!(new("__FOO_BAR__"), "FOO BAR");
}