FunnyString/lib.rs
1/// Returns the character at the index of the given string.
2/// The first character of **string** is at index 0
3///
4/// # Example:
5/// ```rust
6/// let input: &str = "Hello, World!";
7/// let result: char = funny_string::index_string(input, 4);
8/// // result now contains the char 'o'
9/// ```
10pub fn index_string(string: &str, index: i32) -> char {
11 return string.chars().nth(index as usize).unwrap();
12}
13
14/// Returns the substring between the given **begin** index and **end** index.
15/// The first character of **string** is at index 0
16/// - **begin** --> inclusive
17/// - **end** --> exclusive
18///
19/// # Example:
20/// ```rust
21/// let input: &str = "Hello, World!";
22/// let result: String = funny_string::substring(input, 2, 6);
23/// // result now contains the string "llo,"
24/// ```
25pub fn substring(string: &str, begin: i32, end: i32) -> String {
26 return string.chars().skip(begin as usize).take((end - begin) as usize).collect();
27}
28
29/// Replaces the character at the given index and returns the string.
30///
31/// # Example:
32/// ```rust
33/// let input: &str = "Hello, World!";
34/// let result: String = funny_string::replace_char(input, 3, 'X');
35/// // result now contains the string "HelXo, World!"
36/// ```
37pub fn replace_char(string: &str, index: i32, replacement: char) -> String {
38 let index: usize = index as usize;
39 let first = &string[..index];
40 let second = &string[index + 1..];
41 return format!("{}{}{}", first, replacement, second);
42}
43
44/// Replaces a range of characters in **string** with the given **replacement**.
45/// The range is **begin** to **end**.
46///
47/// - **begin** --> inclusive
48/// - **end** --> exclusive
49///
50/// The string with the replaced substring gets returned.
51///
52/// # Example:
53/// ```rust
54/// let input: &str = "Hello, World!";
55/// let result: String = funny_string::replace_substring(input, 1, 5, 'X');
56/// // result now contains the string "HXXXX, World!"
57/// ```
58pub fn replace_substring(string: &str, begin: i32, end: i32, replacement: char) -> String {
59 let begin: usize = begin as usize;
60 let end: usize = end as usize;
61 let mut replacement_substring = "".to_string();
62 for _ in 0..end-begin {
63 replacement_substring.push(replacement);
64 }
65 let first = &string[..begin];
66 let second = &string[end..];
67 return format!("{}{}{}", first, replacement_substring, second);
68}