Skip to main content

rovkit/
stringkit.rs

1use regex::Regex;
2
3pub fn trim(s: &str) -> &str {
4    s.trim()
5}
6
7pub fn to_lower(s: &str) -> String {
8    s.to_lowercase()
9}
10
11pub fn to_upper(s: &str) -> String {
12    s.to_uppercase()
13}
14
15pub fn contains(s: &str, pat: &str) -> bool {
16    s.contains(pat)
17}
18
19pub fn starts_with(s: &str, prefix: &str) -> bool {
20    s.starts_with(prefix)
21}
22
23pub fn ends_with(s: &str, suffix: &str) -> bool {
24    s.ends_with(suffix)
25}
26
27pub fn replace(s: &str, from: &str, to: &str) -> String {
28    s.replacen(from, to, 1)
29}
30
31pub fn replace_all(s: &str, from: &str, to: &str) -> String {
32    s.replace(from, to)
33}
34
35pub fn regex_replace(s: &str, pattern: &str, repl: &str) -> Result<String, regex::Error> {
36    let re = Regex::new(pattern)?;
37    Ok(re.replace_all(s, repl).to_string())
38}
39
40pub fn split(s: &str, sep: &str) -> Vec<String> {
41    s.split(sep).map(|v| v.to_string()).collect()
42}
43
44pub fn join(parts: &[&str], sep: &str) -> String {
45    parts.join(sep)
46}
47
48pub fn to_snake_case(s: &str) -> String {
49    let mut result = String::new();
50    for (i, c) in s.chars().enumerate() {
51        if c.is_uppercase() {
52            if i > 0 {
53                result.push('_');
54            }
55            result.extend(c.to_lowercase());
56        } else {
57            result.push(c);
58        }
59    }
60    result
61}
62
63pub fn to_camel_case(s: &str) -> String {
64    let mut result = String::new();
65    let mut uppercase_next = false;
66    for c in s.chars() {
67        if c == '_' {
68            uppercase_next = true;
69        } else if uppercase_next {
70            result.extend(c.to_uppercase());
71            uppercase_next = false;
72        } else {
73            result.push(c);
74        }
75    }
76    result
77}
78
79pub fn remove_whitespace(s: &str) -> String {
80    s.chars().filter(|c| !c.is_whitespace()).collect()
81}