Skip to content

truncate

Shortens s to at most max_chars characters, ending with suffix when it was cut.

The suffix counts toward the limit. Lengths are in Unicode scalar values (chars), not grapheme clusters. If the suffix alone does not fit, the first max_chars characters of the suffix are returned.

use helpers4::string::truncate;

Cargo feature string (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features string

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.5", default-features = false, features = ["string"] }
pub fn truncate(s: &str, max_chars: usize, suffix: &str) -> String
ParameterTypeDescription
s&strThe text to shorten.
max_charsusizeThe maximum length of the result, suffix included.
suffix&strAppended when s was cut.

String

use helpers4::string::truncate;

assert_eq!(truncate("Hello, world", 8, "..."), "Hello...");
assert_eq!(truncate("short", 8, "..."), "short");
assert_eq!(truncate("Hello", 2, "..."), "..");

src/string/truncate.rs