Wrap text in Rust

textwrap wrap

Using textwrap it is very easy to take a line of text and split it up into chunks that are all less then a certain number of characters.

I needed this in the project creating the banners and the images that are generated from the title of each page on this site to be used when the pages are shared on social networks.

Create a new crate

cargo new wrap
cd wrap

Add the textwrap crate:

cargo add textwrap

This is the code:

examples/wrap/src/main.rs

fn main() {
    let text = "This is some long text that we need to wrap to fit in a given width".to_string();
    println!("{}", text);
    let lines = textwrap::wrap(&text, 28);
    println!("{:#?}", lines);

    let lines = textwrap::wrap(&text, 4);
    println!("{:#?}", lines);
}

This is the result, pretty-printed using # to make it easier to see the new rows:

This is some long text that we need to wrap to fit in a given width
[
    "This is some long text that",
    "we need to wrap to fit in a",
    "given width",
]
[
    "This",
    "is",
    "some",
    "long",
    "text",
    "that",
    "we",
    "need",
    "to",
    "wrap",
    "to",
    "fit",
    "in a",
    "give",
    "n",
    "widt",
    "h",
]

Related Pages

Create image for social networks

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo