Skip to content

Instantly share code, notes, and snippets.

@George-Payne
Last active November 19, 2018 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save George-Payne/af4b2f64757bbbcf6e759eefd770e343 to your computer and use it in GitHub Desktop.
Save George-Payne/af4b2f64757bbbcf6e759eefd770e343 to your computer and use it in GitHub Desktop.
Text chunking
fn chunk_text(width: i32, text: &str) -> Vec<String> {
text.split_whitespace().fold(vec![], |mut acc, word| {
let length = acc.len();
if length > 0 && &acc[length - 1].len() + word.len() + 1 <= width as usize {
acc[length - 1] = [&acc[length - 1], word].join(" ");
} else {
acc.push(word.to_string());
}
acc
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment