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

Fluent Builder

The Str::of() builder provides a chainable API for complex string transformations.

Basic Usage

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

let result = Str::of("  Hello World  ")
    .trim()
    .lower()
    .replace(" ", "_")
    .value();

assert_eq!(result, "hello_world");
}

String Transformations

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

Str::of("hello")
    .trim()           // "hello"
    .lower()          // "hello"
    .upper()          // "HELLO"
    .title()          // "Hello"
    .replace("o", "0") // "hell0"
    .reverse()        // "0lleh"
    .value()
}

Conditional Transformations

when

Applies transformation conditionally:

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

let result = Str::of("hello")
    .when(true, |s| s.append(" world"))
    .when(false, |s| s.append(" hidden"))
    .value();

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

when_empty

Applies transformation when string is empty:

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

let result = Str::of("")
    .when_empty(|s| s.append("default"))
    .value();

assert_eq!(result, "default");
}

when_contains

Applies transformation when string contains a substring:

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

let result = Str::of("user@example.com")
    .when_contains("@", |s| s.replace("@", " [at] "))
    .value();

assert_eq!(result, "user [at] example.com");
}

Value Extraction

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

let s = Str::of("hello");

assert_eq!(s.len(), 5);
assert!(!s.is_empty());
assert!(s.contains("ell"));
}

Piping Custom Functions

Use pipe to apply custom transformations:

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

let result = Str::of("hello")
    .pipe(|s| s.to_uppercase())
    .pipe(|s| format!("{}!", s))
    .value();

assert_eq!(result, "HELLO!");
}

Side Effects with Tap

tap allows side effects without changing the value:

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

let mut log = Vec::new();
let result = Str::of("hello")
    .tap(|s| log.push(s.len()))
    .tap(|s| log.push(s.chars().count()))
    .value();

assert_eq!(result, "hello");
assert_eq!(log, vec![5, 5]);
}

Real-World Example

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

fn format_username(name: &str) -> String {
    Str::of(name)
        .trim()
        .lower()
        .when_empty(|s| s.append("anonymous"))
        .replace(" ", "_")
        .prepend("@")
        .value()
}

assert_eq!(format_username("  JohnDoe  "), "@johndoe");
assert_eq!(format_username("   "), "@anonymous");
}

See Also