const_format

Macro str_replace

Source
macro_rules! str_replace {
    ($input:expr, $pattern:expr, $replace_with:expr $(,)*) => { ... };
}
Expand description

Replaces all the instances of $pattern in $input (a &'static str constant) with $replace_with (a &'static str constant).

§Signature

This macro acts like a function of this signature:

fn str_replace(
    input: &'static str,
    pattern: impl Pattern,
    replace_with: &'static str,
) -> &'static str

and is evaluated at compile-time.

Where pattern can be any of these types:

  • &'static str

  • char

  • u8: required to be ascii (0 up to 127 inclusive).

§Example

use const_format::str_replace;

// Passing a string pattern
assert_eq!(
    str_replace!("The incredible shrinking man.", "i", "eee"),
    "The eeencredeeeble shreeenkeeeng man.",
);

// Passing a char pattern
assert_eq!(
    str_replace!("The incredible shrinking man.", ' ', "---"),
    "The---incredible---shrinking---man.",
);

// Passing an ascii u8 pattern.
assert_eq!(
    str_replace!("The incredible shrinking man.", b'i', "eee"),
    "The eeencredeeeble shreeenkeeeng man.",
);

// Removing all instances of the pattern
assert_eq!(
    str_replace!("remove haire", "re", ""),
    "move hai",
);

// This shows that all the arguments can be `const`s, they don't have to be literals.
{
    const IN: &str = "Foo Boo Patoo";
    const REPLACING: &str = "oo";
    const REPLACE_WITH: &str = "uh";
    assert_eq!(str_replace!(IN, REPLACING, REPLACE_WITH), "Fuh Buh Patuh");
}