fn magic(input: &str) -> String { let mut output: String = input // trim leading and trailing space .trim() // split into lines .lines() .flat_map(|part| { // for each line part // trim leading and trailing space .trim() // split on whitespace // including the space where the string was split .split_inclusive(char::is_whitespace) // filter out substrings containing only whitespace .filter(|part| !part.trim().is_empty()) // add a newline after each line .chain(["\n"]) }) // collect into a String .collect(); // remove the last newline output.truncate(output.len() - 1); output }
#[test] fn test() { // assert_eq!(&magic(" "), " "); assert_eq!( &magic(" a l l lower "), "a l l lower" ); assert_eq!( &magic(" i need\nnew lines \n\nmany times "), "i need\nnew lines\n\nmany times" ); assert_eq!(&magic(" à la "), "à la"); }
|