Make the string a list of separatedd strings
In this task I want you to take a string with ascii text and split it into a list of strings with all the words from the original string separated by a string containing a separator. Also given to you. For example:
input: string:"Lorem ipsum dolor sit amet", separator: '_'
output: ["Lorem", "_", "ipsum", "_", "dolor", "_", "sit", "_", "amet"]
fn separate_strings(list: &str, separator: char) -> Vec<String> {
let mut res: Vec<String> = Vec::new();
let words: Vec<&str> = list.split(" ").collect();
let total = words.len();
for (index, word) in words.iter().enumerate() {
res.push(String::from(*word));
if index < total - 1 {
res.push(separator.to_string());
}
}
res
}
// Add your tests here.
// See https://doc.rust-lang.org/stable/rust-by-example/testing/unit_testing.html
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_add_one_separator_in_the_middle() {
let sol = separate_strings("Hello world.", '?');
let expected = vec!["Hello", "?", "world."];
for exp in expected {
assert!( sol.iter().any(|s| s == exp), "couldn't find: {exp} in {sol:?}" );
}
}
#[test]
fn should_have_separator() {
let separator = '#';
let sol = separate_strings("Lorem ipsum dolor sit amet", separator);
assert!(sol.iter().any(|s| s == &separator.to_string()), "The separator {separator} was not found in the soultion.");
}
#[test]
fn should_add_separator() {
let sol = separate_strings("Lorem ipsum dolor sit amet", '_');
let expected = vec!["Lorem", "_", "ipsum", "_", "dolor", "_", "sit", "_", "amet"];
for exp in expected {
assert!( sol.iter().any(|s| s == exp), "couldn't find: {exp} in {sol:?}" );
}
}
}