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
53
54
55
56
57
58
59
60
61
62
/// Returns the part of target string from the start index up to and excluding the end index.
///
/// # Arguments
///
/// * `s` - The string to process.
/// * `start` - The index of the first character to include in the returned substring.
/// * `end` - The index of the first character to exclude from the returned substring.
///
/// # Returns
///
/// Returns the substring.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use rufl::string;
///
/// assert_eq!("", string::substring("abcde", 0, 0));
///
/// assert_eq!("ab", string::substring("abcde", 0, 2));
///
/// assert_eq!("abcde", string::substring("abcde", 0, 10));
///
/// ```
pub fn substring(s: impl AsRef<str>, start: usize, end: usize) -> String {
if start > end || start == end {
return String::new();
}
// let end = s
// .as_ref()
// .chars()
// .map(|c| c.len_utf8())
// .take(end - start)
// .sum();
// s.as_ref()[..end].to_string()
s.as_ref().chars().skip(start).take(end - start).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_substring() {
assert_eq!("", substring("abcde", 0, 0));
assert_eq!("a", substring("abcde", 0, 1));
assert_eq!("ab", substring("abcde", 0, 2));
assert_eq!("abcde", substring("abcde", 0, 10));
assert_eq!("żó", substring("żółć", 0, 2));
assert_eq!("a̐", substring("a̐éö̲", 0, 2));
assert_eq!("你好", substring("你好你好", 0, 2));
assert_eq!("♥♥", substring("♥♥♥♥♥♥♥♥♥", 0, 2));
}
}