pythonic_helper/
strings.rs

1/// Count how many times a substring appears in another string
2/// 
3/// # Example
4/// ```
5/// use pythonic_helper::strings::count;
6/// 
7/// let text = String::from("Hello World");
8/// let substring = "l";
9/// let count = count(text, substring);
10/// 
11/// assert_eq!(count, 3);
12/// ```
13pub fn count(text: String, substring: &str) -> usize {
14    if text.is_empty() || substring.is_empty() {
15        return 0_usize;
16    }
17    
18    text.matches(substring).count()
19}
20
21/// Split a string into a vector of strings
22/// 
23/// # Example
24/// ```
25/// use pythonic_helper::strings::split;
26/// 
27/// let text = String::from("Hello World");
28/// let delimiter = " ";
29/// let words = split(text, Some(delimiter));
30/// 
31/// let expected = vec![String::from("Hello"), String::from("World")];
32/// assert_eq!(words, expected);
33/// assert_eq!(words.len(), 2);
34/// ```
35pub fn split(text: String, delimiter: Option<&str>) -> Vec<String> {
36    let delimiter = delimiter.unwrap_or(" ");
37
38    if text.is_empty() || delimiter.is_empty() {
39        return vec![];
40    }
41
42    text.split(delimiter).map(|s| s.to_string()).collect()
43}
44
45
46#[cfg(test)]
47mod tests {
48    use super::count;
49
50    #[test]
51    fn test_count_empty_string() {
52        let text = String::from("");
53        let substring = "";
54
55        assert_eq!(count(text, substring), 0);
56    }
57
58    #[test]
59    fn test_count_no_match() {
60        let text = String::from("Hello World");
61        let substring = "abc";
62
63        assert_eq!(count(text, substring), 0);
64    }
65}