Str

public protocol Str

Shared read-only protocol for String and StringSlice.

Requires exactly one method from conformers: asSlice(). All read-only methods are defined once in extend Str and inherited by both types automatically.

Properties

public var byteCount: Int64 { get }

Number of UTF-8 bytes. O(1).

Examples

"hello".byteCount; // 5 "\u{00E9}".byteCount; // 2 (é is two UTF-8 bytes)
public var bytes: BytesView { get }

View over the raw UTF-8 bytes.

Examples

"hi".bytes.count; // 2
public var chars: CharsView { get }

View over Unicode code points.

Examples

"caf\u{00E9}".chars.count; // 4
public var graphemes: GraphemesView { get }

View over grapheme clusters (user-perceived characters).

Examples

"caf\u{00E9}".graphemes.count; // 4
public var isEmpty: Bool { get }

True when the string contains no bytes.

Examples

"".isEmpty; // true "hello".isEmpty; // false
public var lines: LinesView { get }

View over lines, recognising \n, \r\n, and \r.

Examples

"a\nb\nc".lines.count; // 3

Methods

public func asByteSlice() -> ArraySlice[UInt8]

Returns a non-owning ArraySlice[UInt8] view over this string's raw UTF-8 bytes — no copy, no allocation. The slice borrows the live string buffer, so it must not outlive the string (or any mutation of it). O(1).

Use this to hand the bytes to a sink (a socket, a hasher, an FFI call) without materializing an Array[UInt8] via toBytes().

Examples

let bytes = "Hi".asByteSlice(); bytes.count; // 2
func asSlice() -> StringSlice
public func caseFolded() -> String

Returns a new string with Unicode case folding applied to each code point.

Case folding maps characters to a canonical form suitable for case-insensitive comparison. Currently single-char folds only (e.g. Aa); multi-char expansions like ßss are not yet supported.

Examples

"Hello".caseFolded(); // "hello"
public func contains(String) -> Bool

Returns true if substring appears anywhere in this string.

Examples

"hello world".contains(substring: "world"); // true "hello world".contains(substring: "xyz"); // false
public func contains(where: (Char) -> Bool) -> Bool

Returns true if any code point matches predicate.

Examples

"abc123".contains(where: { (c) in c.isAsciiDigit }); // true
public func ends(with: String) -> Bool

Returns true if this string ends with suffix.

Empty suffix always returns true. Comparison is byte-wise.

Examples

"hello".ends(with: "llo"); // true "hello".ends(with: "xyz"); // false
public func equalsCaseInsensitive(String) -> Bool

Compares two strings for equality after Unicode case folding.

Folds each string to its case-folded form and compares the results byte-wise. Not normalization-aware — é (U+00E9) and e\u{0301} are still considered different.

Examples

"Hello".equalsCaseInsensitive("HELLO"); // true "Hello".equalsCaseInsensitive("World"); // false
public func equalsIgnoreAsciiCase[__opaque_0](__opaque_0) -> Bool where __opaque_0: Str

ASCII case-insensitive equality — folds only AZaz; bytes >= 0x80 must match exactly.

Allocates nothing: it compares the raw UTF-8 bytes in place behind a length fast-path, so it is far cheaper than equalsCaseInsensitive, which builds two Unicode-folded Strings. Use it for ASCII tokens such as HTTP header names, where Unicode folding is unnecessary.

Examples

"Content-Type".equalsIgnoreAsciiCase("content-type"); // true "Content-Type".equalsIgnoreAsciiCase("Host"); // false
public func firstIndex(of: String) -> ByteIndex?

Returns the byte index of the first occurrence of substring, or None if not found.

The empty substring matches at the start. Uses memmem for efficient byte-level search.

Examples

"hello world".firstIndex(of: "world"); // Some(ByteIndex(6)) "hello world".firstIndex(of: "xyz"); // None
public func lastIndex(of: String) -> ByteIndex?

Returns the byte index of the last occurrence of substring, or None if not found.

Scans from the left using repeated memmem calls, keeping the last match position.

Examples

"abcabc".lastIndex(of: "abc"); // Some(ByteIndex(3)) "abcabc".lastIndex(of: "xyz"); // None
public func lowercased() -> String

Returns the lowercase form using full Unicode case mapping.

Locale-independent. Handles multi-character expansions (e.g. Turkish dotted I). All-ASCII strings with no uppercase letters short-circuit to toOwned() (no per-char decode).

Examples

"Hello".lowercased(); // "hello" "\u{0130}".lowercased(); // "i\u{0307}"
public func lowercasedAscii() -> String

Returns a copy with only ASCII letters lowercased; non-ASCII bytes pass through unchanged.

Cheap byte-level scan with no Unicode tables. For full Unicode case mapping, use lowercased().

Examples

"H\u{00E9}LLO".lowercasedAscii(); // "h\u{00E9}llo"
public func pad(leading: Int64, with: Char) -> String

Returns the string padded at the start with char so the total code-point count is at least length.

If the string is already at least length code points long, returns a copy unchanged.

Examples

"42".pad(leading: 5, with: '0'); // "00042"
public func pad(trailing: Int64, with: Char) -> String

Returns the string padded at the end with char so the total code-point count is at least length.

If the string is already at least length code points long, returns a copy unchanged.

Examples

"42".pad(trailing: 5, with: '.'); // "42..."
public func repeated(Int64) -> String

Returns this string concatenated with itself count times.

Non-positive count returns the empty string. Pre-allocates the result buffer for the exact final length.

Examples

"ab".repeated(3); // "ababab" "ab".repeated(0); // ""
public func replaced(String, with: String) -> String

Returns a copy with every occurrence of pattern replaced by replacement.

Empty pattern is a no-op (returns a copy). Searches greedily from the left and skips past each replacement so substituted text is not re-matched.

Examples

"hello world".replaced("o", with: "0"); // "hell0 w0rld" "abcabc".replaced("ab", with: "ABCD"); // "ABCDcABCDc"
public func split(String) -> SplitView

Returns a lazy view that splits on separator, yielding zero-copy StringSlice segments.

The empty separator is special-cased to split per code point. Adjacent separators produce empty segments.

Examples

"a,b,c".split(",").collect(); // ["a", "b", "c"] "a,,b".split(",").count; // 3 (empty segment preserved)
public func split(where: consuming (Char) -> Bool) -> SplitWhereView

Returns a lazy view that splits at every code point matching predicate, yielding zero-copy StringSlice segments.

The matching characters are not included in any segment.

Examples

"hello world".split(where: { (c) in c.isWhitespace }).count; // 2
public func starts(with: String) -> Bool

Returns true if this string starts with prefix.

Empty prefix always returns true. Comparison is byte-wise.

Examples

"hello".starts(with: "hel"); // true "hello".starts(with: "xyz"); // false
public func titlecased() -> String

Returns the titlecase form using full Unicode case mapping.

Word boundaries are detected by Char.isWhitespace; the first non-space character of each run is titlecased and the rest lowercased.

Examples

"hello world".titlecased(); // "Hello World" "FOO BAR".titlecased(); // "Foo Bar"
public func toBytes() -> Array[UInt8]

Copies this string's raw UTF-8 bytes into a new Array[UInt8].

Single bulk copy of the whole byte range (one buffer clone + one memcpy-style loop), so it is O(n) — unlike appending byte by byte, where each COW write re-clones the whole buffer and the total cost is O(n²).

Examples

"Hi".toBytes().count; // 2 "Hi".toBytes()(0); // 72 ('H')
public func toOwned() -> String

Copies this string's bytes into a new independent String.

For String, this is equivalent to clone(). For StringSlice, it copies only the slice's bytes, releasing the reference to the source buffer.

Examples

let slice = "hello world".asSlice(); let owned = slice.toOwned(); // independent copy
public func trimmed() -> StringSlice

Returns a zero-copy slice with leading and trailing ASCII whitespace removed.

Whitespace characters: space (' '), tab ('\t'), newline ('\n'), carriage return ('\r'), and form feed ('\x0C'). The returned StringSlice shares the source buffer — no allocation occurs.

Examples

" hello ".trimmed().toOwned(); // "hello" "\t\n".trimmed().isEmpty; // true
public func trimmed(where: (Char) -> Bool) -> StringSlice

Returns a zero-copy slice with leading and trailing code points matching predicate removed.

Decodes the source one Char at a time. Leading characters that satisfy the predicate are skipped; the trailing boundary is the last character that does not match.

Examples

"00042".trimmed(where: { (c) in c.isEqual(to: '0') }).toOwned(); // "42"
public func trimmedEnd() -> StringSlice

Returns a zero-copy slice with trailing whitespace removed.

See trimmed() for the whitespace set. Leading whitespace is preserved.

Examples

" hello ".trimmedEnd().toOwned(); // " hello"
public func trimmedEnd(where: (Char) -> Bool) -> StringSlice

Returns a zero-copy slice with trailing code points matching predicate removed. Leading matches are preserved.

Examples

"abc000".trimmedEnd(where: { (c) in c.isEqual(to: '0') }).toOwned(); // "abc"
public func trimmedStart() -> StringSlice

Returns a zero-copy slice with leading whitespace removed.

See trimmed() for the whitespace set. Trailing whitespace is preserved.

Examples

" hello ".trimmedStart().toOwned(); // "hello "
public func trimmedStart(where: (Char) -> Bool) -> StringSlice

Returns a zero-copy slice with leading code points matching predicate removed. Trailing matches are preserved.

Examples

"000abc".trimmedStart(where: { (c) in c.isEqual(to: '0') }).toOwned(); // "abc"
public func uppercased() -> String

Returns the uppercase form using full Unicode case mapping.

Locale-independent. Handles multi-character expansions (e.g. ßSS). All-ASCII strings with no lowercase letters short-circuit to toOwned().

Examples

"hello".uppercased(); // "HELLO" "stra\u{00DF}e".uppercased(); // "STRASSE"
public func uppercasedAscii() -> String

Returns a copy with only ASCII letters uppercased; non-ASCII bytes pass through unchanged.

Cheap byte-level scan with no Unicode tables. For full Unicode case mapping, use uppercased().

Examples

"h\u{00E9}llo".uppercasedAscii(); // "H\u{00E9}LLO"

ImplementsIterable

Associated Types

type Item

The element type that iteration yields.

type TargetIterator

The concrete iterator type returned by iter(). Constrained so TargetIterator.Item matches Self.Item.

Methods

public func iter() -> CharsIterator

Returns a CharsIterator over the code points.

Required by Iterable. Each call returns a fresh iterator; the source is reusable.

Examples

for c in "abc" { ... } // iterates 'a', 'b', 'c'

ImplementsEquatable

Associated Types

type Output = Bool

Methods

public func equal(to: Self) -> Bool

Bridges Equal.equal(to:) to Equatable.isEqual(to:).

public func isEqual(to: Self) -> Bool

Returns true if both strings have the same byte sequence.

Pure byte-wise equality — not normalization-aware. For case-insensitive comparison, see equalsCaseInsensitive.

Examples

"abc".isEqual(to: "abc"); // true "abc".isEqual(to: "ABC"); // false
public func notEqual(to: Self) -> Bool

Default !=: delegates to == so there's a single source of truth.

ImplementsComparable

Associated Types

type Output = Bool

Methods

public func compare(Self) -> Ordering

Lexicographic byte-wise comparison.

Returns Less / Equal / Greater according to the first differing byte; if one string is a prefix of the other, the shorter is less.

Examples

"abc".compare("abd"); // Less "abc".compare("ab"); // Greater
public func greaterThan(Self) -> Bool

> derived from compare.

public func greaterThanOrEqual(Self) -> Bool

>= derived from compare.

public func isAtLeast(Self) -> Bool

start.. lower-bound check, derived from compare.

public func isAtMost(Self) -> Bool

..=end upper-bound check, derived from compare.

public func isBelow(Self) -> Bool

..<end upper-bound check, derived from compare.

public func lessThan(Self) -> Bool

< derived from compare.

public func lessThanOrEqual(Self) -> Bool

<= derived from compare.

ImplementsHashable

Methods

public func hash[H](into: mutating H) where H: Hasher

Hashes the byte content into hasher.

ImplementsFormattable

Methods

public func format(into: mutating StringBuilder, FormatOptions)

Formats the string using the given options.

Examples

"hi".format(FormatOptions(width: 5)); // "hi "
public func formatted(FormatOptions) -> String

Returns this value rendered as a String.

Convenience wrapper: creates a StringBuilder, calls format(into:), and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with format(into:).

Defined in lang/std/text/str.ks