Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

String Utilities

Comprehensive string manipulation functions for Rust.

Case Conversion

to_snake_case

Converts a string to snake_case:

#![allow(unused)]
fn main() {
use rok_utils::to_snake_case;

assert_eq!(to_snake_case("HelloWorld"), "hello_world");
assert_eq!(to_snake_case("XMLParser"), "xml_parser");
assert_eq!(to_snake_case("TestV2"), "test_v2");
}

to_camel_case

Converts a string to camelCase:

#![allow(unused)]
fn main() {
use rok_utils::to_camel_case;

assert_eq!(to_camel_case("hello_world"), "helloWorld");
assert_eq!(to_camel_case("test-string"), "testString");
}

to_kebab_case

Converts a string to kebab-case:

#![allow(unused)]
fn main() {
use rok_utils::to_kebab_case;

assert_eq!(to_kebab_case("HelloWorld"), "hello-world");
assert_eq!(to_kebab_case("Hello_World"), "hello-world");
}

to_pascal_case

Converts a string to PascalCase:

#![allow(unused)]
fn main() {
use rok_utils::to_pascal_case;

assert_eq!(to_pascal_case("hello_world"), "HelloWorld");
assert_eq!(to_pascal_case("test-string"), "TestString");
}

Transformations

slug

Creates a URL-friendly slug:

#![allow(unused)]
fn main() {
use rok_utils::slug;

assert_eq!(slug("Hello World!"), "hello-world");
assert_eq!(slug("O'Reilly's Guide", '_'), "oreillys_guide");
}

truncate

Truncates a string to a specified length:

#![allow(unused)]
fn main() {
use rok_utils::truncate;

assert_eq!(truncate("Hello World!", 5), "Hello...");
assert_eq!(truncate("Hi", 10), "Hi");
}

squish

Collapses whitespace and trims:

#![allow(unused)]
fn main() {
use rok_utils::squish;

assert_eq!(squish("  hello   world  "), "hello world");
}

wrap

Wraps a string with prefix and suffix:

#![allow(unused)]
fn main() {
use rok_utils::wrap;

assert_eq!(wrap("content", "[", "]"), "[content]");
}

Inspection

is_empty

Checks if a string is empty (after trimming):

#![allow(unused)]
fn main() {
use rok_utils::is_empty;

assert!(is_empty("  "));
assert!(!is_empty(" hello "));
}

contains

Checks if string contains a substring:

#![allow(unused)]
fn main() {
use rok_utils::contains;

assert!(contains("hello world", "lo"));
assert!(!contains("hello", "xyz"));
}

starts_with / ends_with

#![allow(unused)]
fn main() {
use rok_utils::{starts_with, ends_with};

assert!(starts_with("hello world", "hello"));
assert!(ends_with("hello world", "world"));
}

Pluralization

pluralize

#![allow(unused)]
fn main() {
use rok_utils::pluralize;

assert_eq!(pluralize("cat", 1), "cat");
assert_eq!(pluralize("cat", 2), "cats");
assert_eq!(pluralize("box", 3), "boxes");
}

Requires the unicode feature flag.

See Also