#strings
Xu 0.16.0 API
import: #strings
counts: 55 functions, 33 methods, 7 types, 0 constants, 0 method sets
Split and join text
Use strings to trim text, split it into fields and join the result.
The input is borrowed by trim_space and split; their results are owned values.
Save the complete program as main.xu and run xu run main.xu locally.
@main
#strings
fn main() {
raw := " xu,docs "
clean := strings.trim_space(&raw)
parts := strings.split(&clean, ",")
println(strings.join(parts, " / "))
}
Expected output: xu / docs.
Examples · API declarations
Examples
These sources come from the official examples repository and can be copied or downloaded. Run them with a local Xu SDK in the complete project; network, database, and desktop examples require the corresponding services or assets.
22_standalone_sqlite/main.xu
Required SDK: Xu 0.8.3 · Complete project · Download source
@main
#database/sql/driver
sqlite #github.com/xulang-org/packages/sqlite
#os
#strings
fn remove_if_exists(p string) {
os.remove(p) >>> (err) {
<<
}
}
fn main() int {
println("=== SQLite Standalone Library Integration Test ===")
db_file := "/tmp/xu_sqlite_test.db"
remove_if_exists(strings.clone(&db_file))
// 1. 打开数据库连接
conn := sqlite.open(strings.clone(&db_file))
// 2. 建表
schema := "CREATE TABLE IF NOT EXISTS developers (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INT, salary REAL, active INT);"
res1 := conn.exec(schema, []driver.NamedValue{})
if res1.err.len > 0 {
println("CREATE TABLE error: " + res1.err)
<< 1
}
println("1. Schema created successfully.")
// 3. 参数化插入记录
$args1 := []driver.NamedValue{}
args1.push(driver.NamedValue{name: "name", ordinal: 1, value: "Ada Lovelace"})
args1.push(driver.NamedValue{name: "age", ordinal: 2, value: 36})
args1.push(driver.NamedValue{name: "salary", ordinal: 3, value: 125000.5})
args1.push(driver.NamedValue{name: "active", ordinal: 4, value: true})
res_ins1 := conn.exec("INSERT INTO developers (name, age, salary, active) VALUES (?, ?, ?, ?);", args1)
if res_ins1.err.len > 0 {
println("INSERT 1 error: " + res_ins1.err)
<< 1
}
println("2. Inserted developer 1, id=" + str(res_ins1.last_insert_id) + ", rows_affected=" + str(res_ins1.rows_affected))
// 4. 第二条记录插入
$args2 := []driver.NamedValue{}
args2.push(driver.NamedValue{name: "name", ordinal: 1, value: "Alan Turing"})
args2.push(driver.NamedValue{name: "age", ordinal: 2, value: 41})
args2.push(driver.NamedValue{name: "salary", ordinal: 3, value: 140000.0})
args2.push(driver.NamedValue{name: "active", ordinal: 4, value: true})
res_ins2 := conn.exec("INSERT INTO developers (name, age, salary, active) VALUES (?, ?, ?, ?);", args2)
if res_ins2.err.len > 0 {
println("INSERT 2 error: " + res_ins2.err)
<< 1
}
println("3. Inserted developer 2, id=" + str(res_ins2.last_insert_id) + ", rows_affected=" + str(res_ins2.rows_affected))
// 5. 查询所有记录
rows := conn.query("SELECT id, name, age, salary, active FROM developers ORDER BY id ASC;", []driver.NamedValue{})
if rows.err.len > 0 {
println("QUERY error: " + rows.err)
<< 1
}
println("4. Query returned columns count: " + str(rows.ncols))
$col_str := " Columns: "
for ci in 0:rows.columns.len {
if ci > 0 {
col_str = col_str + ", "
}
col_str = col_str + rows.columns[ci]
}
println(col_str)
nrows := rows.cells.len / rows.ncols
println(" Total rows: " + str(nrows))
$r := 0
while r < nrows {
base := r * rows.ncols
id_str := rows.cells[base]
name_str := rows.cells[base + 1]
age_str := rows.cells[base + 2]
sal_str := rows.cells[base + 3]
act_str := rows.cells[base + 4]
println(" Row " + str(r + 1) + ": id=" + id_str + ", name=" + name_str + ", age=" + age_str + ", salary=" + sal_str + ", active=" + act_str)
r = r + 1
}
// 6. 带参数的查询
$qargs := []driver.NamedValue{}
qargs.push(driver.NamedValue{name: "name", ordinal: 1, value: "Alan Turing"})
rows_filtered := conn.query("SELECT id, name, age FROM developers WHERE name = ?;", qargs)
if rows_filtered.err.len > 0 {
println("FILTERED QUERY error: " + rows_filtered.err)
<< 1
}
if rows_filtered.cells.len >= 3 {
println("5. Parameterized query successful: found " + rows_filtered.cells[1] + ", age=" + rows_filtered.cells[2])
}
// 7. 更新操作
$uargs := []driver.NamedValue{}
uargs.push(driver.NamedValue{name: "age", ordinal: 1, value: 37})
uargs.push(driver.NamedValue{name: "id", ordinal: 2, value: 1})
res_up := conn.exec("UPDATE developers SET age = ? WHERE id = ?;", uargs)
if res_up.err.len > 0 {
println("UPDATE error: " + res_up.err)
<< 1
}
println("6. Updated developer 1: rows_affected=" + str(res_up.rows_affected))
// 8. 事务支持
tx := conn.begin()
$tx_args := []driver.NamedValue{}
tx_args.push(driver.NamedValue{name: "name", ordinal: 1, value: "Grace Hopper"})
tx_args.push(driver.NamedValue{name: "age", ordinal: 2, value: 85})
tx_args.push(driver.NamedValue{name: "salary", ordinal: 3, value: 160000.0})
tx_args.push(driver.NamedValue{name: "active", ordinal: 4, value: true})
res_tx := conn.exec("INSERT INTO developers (name, age, salary, active) VALUES (?, ?, ?, ?);", tx_args)
if res_tx.err.len > 0 {
println("TX INSERT error: " + res_tx.err)
<< 1
}
commit_err := tx.commit()
if commit_err.len > 0 {
println("TX COMMIT error: " + commit_err)
<< 1
}
println("7. Transaction committed successfully.")
// 9. 关闭与清理
conn.close()
remove_if_exists(db_file)
println("=== SQLite Standalone Tests Completed Successfully! ===")
<< 0
}
API declarations
index_of
pub fn index_of(s &string, sub string) int
Purpose
Find the first occurrence of a substring, for example before slicing text around a delimiter.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
sub string- Literal substring to match, not a regular expression.
Returns
Byte offset of the first match, or -1 if absent. An empty substring matches at 0.
Usage notes
- Indexes start at zero and count UTF-8 bytes, not Unicode characters.
Call example
Chinese text indexes count bytes
@main
#strings
fn main() {
text := "你好, Xu"
println(strings.index_of(&text, ","))
println(strings.index_of(&text, "missing"))
}
Expected output:
6
-1
contains
pub fn contains(s &string, sub string) bool
Purpose
Check whether text contains a literal substring when the position itself is not needed.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
sub string- Literal substring to match, not a regular expression.
Returns
true if present, otherwise false; an empty substring always returns true.
trim_space
pub fn trim_space(s &string) string
Purpose
Remove Unicode whitespace from both ends while preserving whitespace inside the text.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
Returns
Text without surrounding whitespace, or an empty string if all characters are whitespace.
repeat
pub fn repeat(s &string, n int) string
Purpose
Repeat the original text a given number of times.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
n int- Repeat count; this implementation returns an empty string when it is zero or negative.
Returns
Repeated text, or an empty string when the input is empty or n <= 0.
join
pub fn join(parts []string, sep string) string
Purpose
Join strings in slice order, inserting a separator only between adjacent elements.
Parameters
parts []string- Strings to join; empty elements are retained.
sep string- Text inserted between elements; an empty string concatenates directly.
Returns
Joined string; an empty slice yields an empty string, and one element gets no separator.
split
pub fn split(s &string, sep string) []string
Purpose
Split text into ordered pieces at a delimiter, preserving empty fields in delimited data.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
sep string- Literal delimiter; an empty string splits into individual Unicode characters.
Returns
A slice of strings without the delimiter. With a nonempty delimiter, consecutive, leading and trailing delimiters produce empty pieces. If no delimiter occurs, the only piece is the original text.
Usage notes
- Empty text with a nonempty delimiter produces one empty piece; empty text with an empty delimiter produces an empty slice.
- Character splitting follows UTF-8 boundaries rather than splitting valid Chinese characters into individual bytes.
- With a one-byte delimiter, each returned piece owns its bytes. It remains valid when the result slice grows.
Call example
Keep empty fields and split Chinese text into characters
@main
#strings
fn main() {
text := "a,,b,"
parts := strings.split(&text, ",")
println(parts.len)
words := "甲乙"
chars := strings.split(&words, "")
println(strings.join(chars, " / "))
}
Expected output:
4
甲 / 乙
has_prefix
pub fn has_prefix(s &string, pre string) bool
Purpose
Check for an exact, case-sensitive match at the beginning of the text.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
pre string- Literal text to match; an empty string also matches.
Returns
true on a match, otherwise false.
has_prefix_borrowed
pub fn has_prefix_borrowed(s &string, pre &string) bool
Purpose
Whether it has prefix borrowed.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
pre &string- prefix (read-only borrow; caller keeps the original; type &string)
Returns
bool — true or false
has_suffix
pub fn has_suffix(s &string, suf string) bool
Purpose
Check for an exact, case-sensitive match at the end of the text.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
suf string- Literal text to match; an empty string also matches.
Returns
true on a match, otherwise false.
ends_with
pub fn ends_with(s &string, suf string) bool
Purpose
Check for an exact, case-sensitive match at the end of the text.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
suf string- Literal text to match; an empty string also matches.
Returns
true on a match, otherwise false.
replace
pub fn replace(s &string, old string, new string, n int) string
Purpose
Replace non-overlapping substring matches from left to right, producing new text without modifying the original.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
old string- Literal substring to replace; an empty string inserts text at character boundaries.
new string- Replacement text for each match; an empty string removes matched text.
n int- Maximum replacements; negative replaces all, while
0 leaves the text unchanged.
Returns
Text after replacement, retaining the original content if no match is found.
Usage notes
- When
old is empty, insertion positions include before the first character, between characters and after the last character.
Call example
Limit the number of replacements
@main
#strings
fn main() {
text := "a-a-a"
println(strings.replace(&text, "a", "x", 2))
println(text)
}
Expected output:
x-x-a
a-a-a
fields
pub fn fields(s &string) []string
Purpose
Split text at Unicode whitespace, omitting empty fields from leading, trailing and repeated separators.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
Returns
Nonempty fields only; empty text or text consisting solely of separators yields an empty slice.
Usage notes
- Use
split when empty fields must be retained.
fields_func
pub fn fields_func(s &string, f fn(int) bool) []string
Purpose
Split text at characters selected by the callback, omitting empty fields from leading, trailing and repeated separators.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
f fn(int) bool- Receives a Unicode code point;
true marks it as a separator.
Returns
Nonempty fields only; empty text or text consisting solely of separators yields an empty slice.
Usage notes
- Use
split when empty fields must be retained.
to_lower
pub fn to_lower(s &string) string
Purpose
Convert characters to lowercase using Unicode simple mappings, leaving other characters unchanged.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
Returns
Converted text without modifying the original string.
Usage notes
- This is not limited to ASCII. Simple mappings do not expand one character into several or apply locale-specific casing.
Call example
Convert non-ASCII letters
@main
#strings
fn main() {
text := "ÄBC"
println(strings.to_lower(&text))
}
Expected output:
äbc
to_upper
pub fn to_upper(s &string) string
Purpose
Convert characters to uppercase using Unicode simple mappings, leaving other characters unchanged.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
Returns
Converted text without modifying the original string.
Usage notes
- This is not limited to ASCII. Simple mappings do not expand one character into several or apply locale-specific casing.
trim_left
pub fn trim_left(s &string, cutset string) string
Purpose
Remove consecutive characters from the beginning while they belong to the supplied set.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
cutset string- Set of Unicode characters that may be removed, not one complete prefix or suffix.
Returns
Trimmed text; an empty character set leaves the original content unchanged.
Usage notes
- Use
trim_prefix or trim_suffix to remove one fixed prefix or suffix.
trim_right
pub fn trim_right(s &string, cutset string) string
Purpose
Remove consecutive characters from the end while they belong to the supplied set.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
cutset string- Set of Unicode characters that may be removed, not one complete prefix or suffix.
Returns
Trimmed text; an empty character set leaves the original content unchanged.
Usage notes
- Use
trim_prefix or trim_suffix to remove one fixed prefix or suffix.
trim
pub fn trim(s &string, cutset string) string
Purpose
Remove consecutive characters from both ends while they belong to the supplied set.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
cutset string- Set of Unicode characters that may be removed, not one complete prefix or suffix.
Returns
Trimmed text; an empty character set leaves the original content unchanged.
Usage notes
- Use
trim_prefix or trim_suffix to remove one fixed prefix or suffix.
trim_prefix
pub fn trim_prefix(s &string, pre string) string
Purpose
Remove one exact prefix if present; the removal is not repeated.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
pre string- Complete prefix to remove, matched case-sensitively.
Returns
Text after removal, or the original content if there is no match.
trim_suffix
pub fn trim_suffix(s &string, suf string) string
Purpose
Remove one exact suffix if present; the removal is not repeated.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
suf string- Complete suffix to remove, matched case-sensitively.
Returns
Text after removal, or the original content if there is no match.
compare
pub fn compare(a &string, b &string) int
Purpose
Compare two strings lexicographically by bytes.
Parameters
a &string- Left-hand text.
b &string- Right-hand text.
Returns
Negative when a precedes b, zero when equal, positive when it follows.
Usage notes
- Compare UTF-8 bytes in order, without case conversion or locale-specific collation.
index_byte
pub fn index_byte(s &string, c int) int
Purpose
Find a single byte forward, for example an ASCII punctuation or protocol delimiter.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
c int- Byte to locate, normally in
0..255.
Returns
Byte offset of the match, or -1 if absent.
Usage notes
- Indexes start at zero and count UTF-8 bytes, not Unicode characters.
- This searches bytes; use
index_rune for a complete Unicode character.
last_index
pub fn last_index(s &string, sub string) int
Purpose
Search backward for the last occurrence of a substring.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
sub string- Literal substring to match, not a regular expression.
Returns
Byte offset of the last match, or -1 if absent. An empty substring returns s.len.
Usage notes
- Indexes start at zero and count UTF-8 bytes, not Unicode characters.
last_index_byte
pub fn last_index_byte(s &string, c int) int
Purpose
Find a single byte backward, for example an ASCII punctuation or protocol delimiter.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
c int- Byte to locate, normally in
0..255.
Returns
Byte offset of the match, or -1 if absent.
Usage notes
- Indexes start at zero and count UTF-8 bytes, not Unicode characters.
- This searches bytes; use
index_rune for a complete Unicode character.
count
pub fn count(s &string, sub string) int
Purpose
Count non-overlapping occurrences of a literal substring.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
sub string- Literal substring to match, not a regular expression.
Returns
Number of matches, or 0 if absent. An empty substring counts character boundaries: the Unicode character count plus 1.
Usage notes
- For example,
"aa" occurs once in "aaa"; matched bytes are not reused.
Call example
Count substring matches and empty boundaries
@main
#strings
fn main() {
text := "aaa"
println(strings.count(&text, "aa"))
words := "甲乙"
println(strings.count(&words, ""))
}
Expected output:
1
3
split_n
pub fn split_n(s &string, sep string, n int) []string
Purpose
Split text with a limit on the number of pieces, keeping any unsplit remainder in the last piece.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
sep string- Literal delimiter; an empty string splits at Unicode character boundaries.
n int- Maximum number of pieces:
0 returns none, a negative value removes the limit, and 1 keeps the text whole.
Returns
Ordered pieces, at most n when positive; n < 0 behaves like split.
Usage notes
- At most
n - 1 splits are made: n limits pieces, not delimiter matches.
replace_all
pub fn replace_all(s &string, old string, new string) string
Purpose
Replace non-overlapping substring matches from left to right, producing new text without modifying the original.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
old string- Literal substring to replace; an empty string inserts text at character boundaries.
new string- Replacement text for each match; an empty string removes matched text.
Returns
Text after replacement, retaining the original content if no match is found.
Usage notes
- When
old is empty, insertion positions include before the first character, between characters and after the last character.
equal_fold
pub fn equal_fold(a &string, b &string) bool
Purpose
Compare text using Unicode simple case folding.
Parameters
a &string- First text to compare.
b &string- Second text to compare.
Returns
true when the texts differ only by supported case mappings; otherwise false.
Usage notes
- Does not trim whitespace, normalize Unicode, or perform multi-character case expansion.
struct Cut
pub struct Cut {
pub before string
pub after string
pub found bool
}
Purpose
Structure encapsulating before, after, found.
Public fields
before string- field (string)
after string- field (string)
found bool- field (bool)
cut
pub fn cut(s &string, sep string) Cut
Purpose
Cut text at the first delimiter; inspect found to distinguish an absent delimiter from an empty piece.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
sep string- Complete delimiter to match; the pieces do not include it.
Returns
Cut.before and Cut.after hold the text before and after the delimiter; found reports a match. Without a match, before is the original text and after is empty.
Usage notes
- An empty delimiter matches at the beginning:
before is empty, after is the original text and found is true.
cut_prefix
pub fn cut_prefix(s &string, pre string) Cut
Purpose
Try to remove an exact prefix, reporting whether a match was made.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
pre string- Complete prefix to match.
Returns
The remaining text is stored in Cut.before, while Cut.after is always empty. found reports success; without a match, before holds the original text.
Call example
Check a prefix and read the remainder
@main
#strings
fn main() {
text := "Bearer token123"
result := strings.cut_prefix(&text, "Bearer ")
println(result.found)
println(result.before)
}
Expected output:
true
token123
cut_suffix
pub fn cut_suffix(s &string, suf string) Cut
Purpose
Try to remove an exact suffix, reporting whether a match was made.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
suf string- Complete suffix to match.
Returns
The remaining text is stored in Cut.before, while Cut.after is always empty. found reports success; without a match, before holds the original text.
struct Builder
pub struct Builder {
pub buf string
}
Purpose
Structure encapsulating buf.
Public fields
buf string- buffer
builder
Purpose
Execute builder.
Parameters
No arguments are required.
Returns
Builder — a value of this type
($&Builder) write_string
pub fn (b $&Builder) write_string(s &string) int
Purpose
Operation on $&Builder: write a string and return the byte count.
Parameters
b $&Builder- The
Builder instance used by this call (exclusive borrow).
s &string- source string (read-only borrow; caller keeps the original; type &string)
Returns
int — bytes written
($&Builder) grow
pub fn (b $&Builder) grow(n int)
Purpose
Operation on $&Builder: ensure room for at least n more bytes.
Parameters
b $&Builder- The
Builder instance used by this call (exclusive borrow).
n int- count, length, or limit (int)
Returns
This call does not return a value.
($&Builder) write_view
pub fn (b $&Builder) write_view(s &string, v ByteView) int
Purpose
Operation on $&Builder: write view.
Parameters
b $&Builder- The
Builder instance used by this call (exclusive borrow).
s &string- source string (read-only borrow; caller keeps the original; type &string)
v ByteView- value (ByteView)
Returns
int — a value of this type
($&Builder) write_int
pub fn (b $&Builder) write_int(n int) int
Purpose
Operation on $&Builder: write int.
Parameters
b $&Builder- The
Builder instance used by this call (exclusive borrow).
n int- count, length, or limit (int)
Returns
int — a value of this type
(&Builder) length
pub fn (b &Builder) length() int
Purpose
Operation on &Builder: return the current length.
Parameters
b &Builder- The
Builder instance used by this call (borrow).
Returns
int — a value of this type
(&Builder) text
pub fn (b &Builder) text() string
Purpose
Operation on &Builder: return the current text.
Parameters
b &Builder- The
Builder instance used by this call (borrow).
Returns
string — result string
($&Builder) reset
pub fn (b $&Builder) reset()
Purpose
Operation on $&Builder: clear internal state so the value can be reused.
Parameters
b $&Builder- The
Builder instance used by this call (exclusive borrow).
Returns
This call does not return a value.
index_func
pub fn index_func(s &string, f fn(int) bool) int
Purpose
Visit Unicode characters and locate the first one accepted by the callback.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
f fn(int) bool- Receives a Unicode code point and returns
true for a match, not a single UTF-8 byte.
Returns
Starting byte offset of the match, or -1 when none matches.
Usage notes
- Indexes start at zero and count UTF-8 bytes, not Unicode characters.
last_index_func
pub fn last_index_func(s &string, f fn(int) bool) int
Purpose
Visit Unicode characters and locate the last one accepted by the callback.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
f fn(int) bool- Receives a Unicode code point and returns
true for a match, not a single UTF-8 byte.
Returns
Starting byte offset of the match, or -1 when none matches.
Usage notes
- Indexes start at zero and count UTF-8 bytes, not Unicode characters.
map_bytes
pub fn map_bytes(s &string, f fn(int) int) string
Purpose
Map each byte through f and rebuild the string.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
f fn(int) int- Callback with signature
fn(int) int; pass the function value for this operation to invoke.
Returns
string — result string
struct ByteBuilder
pub struct ByteBuilder {
pub buf []int
pub len int
}
Purpose
growable byte buffer for hot concat paths (compiler / fmt). Keeps buf []int + len int for ui/draw compatibility when reserve is called, while write_byte/write_str/to_string append directly to s.
Public fields
buf []int- buffer
len int- field (int)
new_byte_builder
pub fn new_byte_builder(cap int) ByteBuilder
Purpose
Construct byte builder.
Parameters
cap int- cap (int)
Returns
ByteBuilder — a value of this type
($&ByteBuilder) reserve
pub fn (sb $&ByteBuilder) reserve(extra int)
Purpose
Execute reserve on $&ByteBuilder.
Parameters
sb $&ByteBuilder- The
ByteBuilder instance used by this call (exclusive borrow).
extra int- extra (int)
Returns
This call does not return a value.
($&ByteBuilder) write_byte
pub fn (sb $&ByteBuilder) write_byte(c int)
Purpose
Operation on $&ByteBuilder: write one byte.
Parameters
sb $&ByteBuilder- The
ByteBuilder instance used by this call (exclusive borrow).
c int- byte or character code (int)
Returns
This call does not return a value.
($&ByteBuilder) write_str
pub fn (sb $&ByteBuilder) write_str(s string)
Purpose
Operation on $&ByteBuilder: write a string.
Parameters
sb $&ByteBuilder- The
ByteBuilder instance used by this call (exclusive borrow).
s string- source string (string)
Returns
This call does not return a value.
(ByteBuilder) to_string
pub fn (sb ByteBuilder) to_string() string
Purpose
Operation on ByteBuilder: convert to string.
Parameters
sb ByteBuilder- The
ByteBuilder instance used by this call (value receiver).
Returns
string — result string
clone
pub fn clone(s &string) string
Purpose
Copy into a new independent string.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
Returns
string — result string
See usage example
contains_func
pub fn contains_func(s &string, f fn(int) bool) bool
Purpose
Report whether any byte satisfies the callback.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
f fn(int) bool- Callback with signature
fn(int) bool; pass the function value for this operation to invoke.
Returns
bool — true or false
index_any
pub fn index_any(s &string, chars string) int
Purpose
Find the first character belonging to a set of accepted characters.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
chars string- A set of characters, not a contiguous substring or regular expression.
Returns
Byte offset of a matching character, or -1 if there is no match or the set is empty.
Usage notes
- Indexes start at zero and count UTF-8 bytes, not Unicode characters.
last_index_any
pub fn last_index_any(s &string, chars string) int
Purpose
Find the last character belonging to a set of accepted characters.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
chars string- A set of characters, not a contiguous substring or regular expression.
Returns
Byte offset of a matching character, or -1 if there is no match or the set is empty.
Usage notes
- Indexes start at zero and count UTF-8 bytes, not Unicode characters.
contains_any
pub fn contains_any(s &string, chars string) bool
Purpose
Report whether any byte from the cutset occurs.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
chars string- byte cutset (string)
Returns
bool — true or false
index_rune
pub fn index_rune(s &string, r int) int
Purpose
Find the first occurrence of a Unicode code point.
Parameters
s &string- Original text, passed as a read-only borrow; this call does not modify it.
r int- Unicode code point to find, such as the integer value of a Chinese character.
Returns
Starting byte offset of the character, or -1 if absent or if r is not a valid Unicode scalar value.
Usage notes
- Indexes start at zero and count UTF-8 bytes, not Unicode characters.
contains_rune
pub fn contains_rune(s &string, r int) bool
Purpose
Report whether the rune occurs.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
r int- rune (Unicode code point) (int)
Returns
bool — true or false
split_after
pub fn split_after(s &string, sep string) []string
Purpose
Split after the separator, keeping it on each piece.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
sep string- separator (string)
Returns
[]string — slice result
split_after_n
pub fn split_after_n(s &string, sep string, n int) []string
Purpose
Split after the separator, at most n parts.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
sep string- separator (string)
n int- count, length, or limit (int)
Returns
[]string — slice result
trim_left_func
pub fn trim_left_func(s &string, f fn(int) bool) string
Purpose
Trim leading bytes using the callback.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
f fn(int) bool- Callback with signature
fn(int) bool; pass the function value for this operation to invoke.
Returns
string — result string
trim_right_func
pub fn trim_right_func(s &string, f fn(int) bool) string
Purpose
Trim trailing bytes using the callback.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
f fn(int) bool- Callback with signature
fn(int) bool; pass the function value for this operation to invoke.
Returns
string — result string
trim_func
pub fn trim_func(s &string, f fn(int) bool) string
Purpose
Trim bytes on both ends using the callback.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
f fn(int) bool- Callback with signature
fn(int) bool; pass the function value for this operation to invoke.
Returns
string — result string
to_valid_utf8
pub fn to_valid_utf8(s &string, replacement string) string
Purpose
Replace invalid UTF-8 sequences with replacement.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
replacement string- replacement for invalid sequences (string)
Returns
string — result string
($&Builder) write_byte
pub fn (b $&Builder) write_byte(c int) int
Purpose
Operation on $&Builder: write one byte.
Parameters
b $&Builder- The
Builder instance used by this call (exclusive borrow).
c int- byte or character code (int)
Returns
int — bytes written
($&Builder) write_rune
pub fn (b $&Builder) write_rune(r int) int
Purpose
Operation on $&Builder: write a rune as UTF-8.
Parameters
b $&Builder- The
Builder instance used by this call (exclusive borrow).
r int- rune (Unicode code point) (int)
Returns
int — bytes written
(&Builder) cap
pub fn (b &Builder) cap() int
Purpose
Operation on &Builder: return the capacity.
Parameters
b &Builder- The
Builder instance used by this call (borrow).
Returns
int — a value of this type
struct Replacer
Purpose
Replacer context or state structure.
Public fields
This type has no public fields.
new_replacer
pub fn new_replacer(oldnew <-> string) Replacer
Purpose
Construct replacer. Throws on failure; handle the error or propagate it to the caller.
Parameters
oldnew <-> string- variadic string (seen inside the function as []string)
Returns
Replacer — a value of this type
(&Replacer) replace
pub fn (r &Replacer) replace(s0 &string) string
Purpose
Replace non-overlapping substring matches from left to right, producing new text without modifying the original.
Parameters
r &Replacer- The
Replacer instance used by this call (borrow).
s0 &string- s0 (read-only borrow; caller keeps the original; type &string)
Returns
Text after replacement, retaining the original content if no match is found.
Usage notes
- When
old is empty, insertion positions include before the first character, between characters and after the last character.
Call example
Limit the number of replacements
@main
#strings
fn main() {
text := "a-a-a"
println(strings.replace(&text, "a", "x", 2))
println(text)
}
Expected output:
x-x-a
a-a-a
struct Reader
Purpose
Strings Streaming reader and decoder.
Public fields
This type has no public fields.
struct RuneRead
pub struct RuneRead {
pub ch int
pub size int
}
Purpose
Structure encapsulating ch, size.
Public fields
ch int- character code
size int- field (int)
new_reader
pub fn new_reader(s string) Reader
Purpose
Construct reader.
Parameters
s string- source string (string)
Returns
Reader — a value of this type
(&Reader) size
pub fn (r &Reader) size() int
Purpose
Operation on &Reader: return the size.
Parameters
r &Reader- The
Reader instance used by this call (borrow).
Returns
int — a value of this type
(&Reader) length
pub fn (r &Reader) length() int
Purpose
Operation on &Reader: return the current length.
Parameters
r &Reader- The
Reader instance used by this call (borrow).
Returns
int — a value of this type
($&Reader) reset
pub fn (r $&Reader) reset(s string)
Purpose
Operation on $&Reader: clear internal state so the value can be reused.
Parameters
r $&Reader- The
Reader instance used by this call (exclusive borrow).
s string- source string (string)
Returns
This call does not return a value.
($&Reader) read_n
pub fn (r $&Reader) read_n(n int) string
Purpose
Operation on $&Reader: read at most n bytes; may return shorter or empty at end.
Parameters
r $&Reader- The
Reader instance used by this call (exclusive borrow).
n int- count, length, or limit (int)
Returns
string — result string
($&Reader) read_byte
pub fn (r $&Reader) read_byte() int
Purpose
Operation on $&Reader: read one byte; throws on failure. Throws on failure; handle the error or propagate it to the caller.
Parameters
r $&Reader- The
Reader instance used by this call (exclusive borrow).
Returns
int — a value of this type
($&Reader) unread_byte
pub fn (r $&Reader) unread_byte() int
Purpose
Operation on $&Reader: unread the last byte. Throws on failure; handle the error or propagate it to the caller.
Parameters
r $&Reader- The
Reader instance used by this call (exclusive borrow).
Returns
int — a value of this type
($&Reader) read_rune
pub fn (r $&Reader) read_rune() RuneRead
Purpose
Operation on $&Reader: read one UTF-8 rune. Throws on failure; handle the error or propagate it to the caller.
Parameters
r $&Reader- The
Reader instance used by this call (exclusive borrow).
Returns
RuneRead — a value of this type
($&Reader) unread_rune
pub fn (r $&Reader) unread_rune() int
Purpose
Operation on $&Reader: unread the last rune. Throws on failure; handle the error or propagate it to the caller.
Parameters
r $&Reader- The
Reader instance used by this call (exclusive borrow).
Returns
int — a value of this type
($&Reader) seek
pub fn (r $&Reader) seek(offset int, whence int) int
Purpose
Operation on $&Reader: move the read position. whence 0/1/2 = absolute / relative / from end. Throws on failure; handle the error or propagate it to the caller.
Parameters
r $&Reader- The
Reader instance used by this call (exclusive borrow).
offset int- offset (int)
whence int- seek base: 0 start / 1 current / 2 end (int)
Returns
int — a value of this type
($&Reader) read_at
pub fn (r $&Reader) read_at(n int, off int) string
Purpose
Operation on $&Reader: read at most n bytes starting at offset off. Throws on failure; handle the error or propagate it to the caller.
Parameters
r $&Reader- The
Reader instance used by this call (exclusive borrow).
n int- count, length, or limit (int)
off int- offset (int)
Returns
string — result string
string_capacity
pub fn string_capacity(s &string) int
Purpose
String capacity.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
Returns
int — a value of this type
string_reserve
pub fn string_reserve(s $&string, n int)
Purpose
String reserve.
Parameters
s $&string- source string (exclusive borrow; may modify the original; type $&string)
n int- count, length, or limit (int)
Returns
This call does not return a value.
struct ByteView
pub struct ByteView {
pub off int
pub len int
}
Purpose
Structure encapsulating off, len.
Public fields
off int- offset
len int- field (int)
view_of
pub fn view_of(s &string) ByteView
Purpose
Create a borrowed read-only ByteView over the string.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
Returns
ByteView — a value of this type
view_slice
pub fn view_slice(s &string, off int, n int) ByteView
Purpose
View slice.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
off int- offset (int)
n int- count, length, or limit (int)
Returns
ByteView — a value of this type
(&ByteView) at
pub fn (v &ByteView) at(s &string, i int) int
Purpose
Execute at on &ByteView.
Parameters
v &ByteView- The
ByteView instance used by this call (borrow).
s &string- source string (read-only borrow; caller keeps the original; type &string)
i int- index or integer (int)
Returns
int — a value of this type
(&ByteView) equal
pub fn (v &ByteView) equal(s &string, t &string, w ByteView) bool
Purpose
Operation on &ByteView: report whether the two values are equal.
Parameters
v &ByteView- The
ByteView instance used by this call (borrow).
s &string- source string (read-only borrow; caller keeps the original; type &string)
t &string- t (read-only borrow; caller keeps the original; type &string)
w ByteView- writer or width (ByteView)
Returns
bool — true or false
(&ByteView) compare
pub fn (v &ByteView) compare(s &string, t &string, w ByteView) int
Purpose
Compare two strings lexicographically by bytes.
Parameters
v &ByteView- The
ByteView instance used by this call (borrow).
s &string- source string (read-only borrow; caller keeps the original; type &string)
t &string- t (read-only borrow; caller keeps the original; type &string)
w ByteView- writer or width (ByteView)
Returns
Negative when a precedes b, zero when equal, positive when it follows.
Usage notes
- Compare UTF-8 bytes in order, without case conversion or locale-specific collation.
(&ByteView) index_byte
pub fn (v &ByteView) index_byte(s &string, c int) int
Purpose
Find a single byte forward, for example an ASCII punctuation or protocol delimiter.
Parameters
v &ByteView- The
ByteView instance used by this call (borrow).
s &string- Original text, passed as a read-only borrow; this call does not modify it.
c int- Byte to locate, normally in
0..255.
Returns
Byte offset of the match, or -1 if absent.
Usage notes
- Indexes start at zero and count UTF-8 bytes, not Unicode characters.
- This searches bytes; use
index_rune for a complete Unicode character.
(&ByteView) last_index_byte
pub fn (v &ByteView) last_index_byte(s &string, c int) int
Purpose
Find a single byte backward, for example an ASCII punctuation or protocol delimiter.
Parameters
v &ByteView- The
ByteView instance used by this call (borrow).
s &string- Original text, passed as a read-only borrow; this call does not modify it.
c int- Byte to locate, normally in
0..255.
Returns
Byte offset of the match, or -1 if absent.
Usage notes
- Indexes start at zero and count UTF-8 bytes, not Unicode characters.
- This searches bytes; use
index_rune for a complete Unicode character.
(&ByteView) has_prefix
pub fn (v &ByteView) has_prefix(s &string, pre &string) bool
Purpose
Check for an exact, case-sensitive match at the beginning of the text.
Parameters
v &ByteView- The
ByteView instance used by this call (borrow).
s &string- Original text, passed as a read-only borrow; this call does not modify it.
pre &string- Literal text to match; an empty string also matches.
Returns
true on a match, otherwise false.
(&ByteView) has_suffix
pub fn (v &ByteView) has_suffix(s &string, suf &string) bool
Purpose
Check for an exact, case-sensitive match at the end of the text.
Parameters
v &ByteView- The
ByteView instance used by this call (borrow).
s &string- Original text, passed as a read-only borrow; this call does not modify it.
suf &string- Literal text to match; an empty string also matches.
Returns
true on a match, otherwise false.
(&ByteView) index
pub fn (v &ByteView) index(s &string, sub &string) int
Purpose
Index of sub relative to the window. Empty needle matches at 0. Returns -1 if not found.
Parameters
v &ByteView- The
ByteView instance used by this call (borrow).
s &string- source string (read-only borrow; caller keeps the original; type &string)
sub &string- substring (read-only borrow; caller keeps the original; type &string)
Returns
int — index; see the description for its range and special values