Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fn main() {
- println!("Hello, world!");
- }
- fn justify_words(line: String, length: usize) -> String {
- let cloned_line = line.clone();
- let words = cloned_line.split_whitespace();
- let mut final_line = String::new();
- let mut current_len = 0;
- // println!("-- {:?}", line.split_whitespace().collect::<Vec<&str>>());
- for word in words {
- if current_len + word.len() < length {
- // Add it
- if final_line == "" {
- current_len += word.len();
- final_line = word.to_owned();
- } else {
- final_line = format!("{} {}", final_line, word);
- current_len += word.len() + 1;
- }
- } else {
- //add \n
- final_line = format!("{}\n{}", final_line, word);
- current_len = word.len();
- }
- }
- final_line
- }
- #[cfg(test)]
- mod test {
- use super::*;
- #[test]
- fn test_justify_words() {
- let resp = String::from(
- r#"here is another
- example for
- consensys
- livecoding for
- the ethereum
- blockchain"#,
- );
- assert_eq!(
- justify_words(
- String::from(
- "here is another example for consensys livecoding for the ethereum blockchain"
- ),
- 15
- ),
- resp
- );
- let resp = String::from(
- r#"here
- is my
- other
- text"#,
- );
- assert_eq!(
- justify_words(String::from("here is my other text"), 5),
- resp
- );
- let resp = String::from(
- r#"xxx
- xxxxx
- yyyyy
- dsf-dsf
- kkkk
- dddd
- ssssss"#,
- );
- assert_eq!(
- justify_words(String::from("xxx xxxxx yyyyy dsf-dsf kkkk dddd ssssss"), 7),
- resp
- );
- let resp = String::from(
- r#"here is another
- example for
- consensys
- livecoding for
- the ethereum
- blockchain"#,
- );
- assert_eq!(
- justify_words(
- String::from(
- r#"here is another
- example for consensys livecoding
- for the ethereum blockchain"#
- ),
- 15
- ),
- resp
- );
- let resp = String::from(
- r#"Hi William, what a
- great news ! This
- week for the culture
- interview I can be
- available this
- tuesday or friday
- after 6:00pm CET.
- Let me know if it
- could fit with your
- schedule ?"#,
- );
- assert_eq!(
- justify_words(
- String::from(
- r#"Hi William, what a great news ! This week for the culture interview I can be available this tuesday or friday after 6:00pm CET. Let me know if it could fit with your schedule ?"#
- ),
- 20
- ),
- resp
- );
- let resp = String::from(
- "here is another example for consensys livecoding for the ethereum blockchain",
- );
- assert_eq!(
- justify_words(
- String::from(
- "here is another example for consensys livecoding for the ethereum blockchain"
- ),
- 100
- ),
- resp
- );
- let resp = String::from(
- "here is another example for consensys livecoding for the ethereum blockchain",
- );
- assert_eq!(
- justify_words(
- String::from(
- "here is another example for consensys livecoding for the ethereum blockchain"
- ),
- 100
- ),
- resp
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement