Under heavy development. This site describes the intended 1.0 language. Current features and performance vary. Development status
Sn50SnThe SnAPI programming language
0.2.0 Preview 1 · Frozen documentation

Replace

Creates an owning UTF-8 string with ordinal nonoverlapping replacements.

Sn is under heavy development. Reference extracted from this release’s bundled standard library. Public API examples are not an exhaustive compatibility test. Read the matching release guide for tested workflows and limitations. Read the status →

Module std.text

import std.text;

Public declaration contracts and authored examples. A page can document several related symbols. Implementation bodies are excluded.

fn

pub const fn TryReplace(Text: str, Search: str, Replacement: str) -> Result<String, AllocationError>

Creates an owning UTF-8 string with ordinal nonoverlapping replacements. Text: Valid UTF-8 input, borrowed only for this operation. Search: Valid UTF-8 pattern; empty inserts at every scalar boundary. Replacement: Valid UTF-8 bytes copied for each admitted match. Return: Owning String, or recoverable AllocationError with no partial result. Note: Uses the ordinal Find search cost; never rescans inserted replacement bytes.

Example

module example.text_replacement;
from std.text import TryReplace;
// Transient owning strings stay inside the constant frame; only its scalar result escapes.
const fn VerifyConstantReplacement() -> i32 {
    switch TryReplace("λ/path/path", "path", "leaf") {
        case .Ok { Value = Changed } => {
            if Changed.View != "λ/leaf/leaf" { return 1; }
        }
        case .Err { Error = _ } => return 2;
    }
    switch TryReplace("λA", "", "-") {
        case .Ok { Value = Changed } => {
            if Changed.View != "-λ-A-" { return 3; }
        }
        case .Err { Error = _ } => return 4;
    }
    switch TryReplace("aaa", "aa", "X") {
        case .Ok { Value = Changed } => {
            if Changed.View != "Xa" { return 5; }
        }
        case .Err { Error = _ } => return 6;
    }
    return 0;
}
const ConstantStatus: i32 = VerifyConstantReplacement();
// Runtime parameters keep this dual-stage call on its ordinary runtime path.
fn VerifyRuntimeReplacement(Text: str, Search: str, Replacement: str, Expected: str) -> bool {
    switch TryReplace(Text, Search, Replacement) {
        case .Ok { Value = Changed } => return Changed.View == Expected;
        case .Err { Error = _ } => return false;
    }
}
fn Main() -> i32 {
    if ConstantStatus != 0 { return ConstantStatus; }
    if !VerifyRuntimeReplacement("λ/path/path", "path", "leaf", "λ/leaf/leaf") { return 7; }
    if !VerifyRuntimeReplacement("λA", "", "-", "-λ-A-") { return 8; }
    if !VerifyRuntimeReplacement("aaa", "aa", "X", "Xa") { return 9; }
    return 0;
}
Documentation snapshot: October 24, 2026 About versions ↗
Searching Development · language & standard library