Standard library · Text

str

Everything to do with text: searching, slicing, replacing, digits, case, and building long strings.

import str

The str package is the one you will reach for most. Anywhere you touch text, from reading user input to building output, its functions apply.

One thing to know before you start: Salam strings are UTF-8. In UTF-8 an English letter is one byte, while a letter in most other scripts takes two or more. That is why most of these functions come in two forms: Len, Substr and IndexOf work in bytes and are fast, while CharCount, CharSubstr and CharFind work in characters. Wherever the count or the cut has to match what the reader sees, use the character form.

One step further out is the "grapheme": what a reader sees as a single letter. A letter with an accent is two characters but one grapheme, and a family emoji is seven characters but one grapheme. For reversing or cutting text that carries marks or emoji, the grapheme functions are the safe ones.

Three methods also sit on every string and need no import: text.starts_with("salam"), text.ends_with(".txt") and text.includes("world"). All three return true or false and behave the same on every backend.

Neighbouring packages: unicode classifies and converts single code points, fmt pads and fills templates, conv parses numbers, regex matches patterns, and arabic normalises Persian and Arabic letters.

Things that catch people out:

•

Upper and Lower change only the ASCII letters A to Z: Upper("café") is CAFé. For other scripts map each code point with unicode.ToUpper or unicode.ToLower; to compare without case use EqualFold, which does follow the full Unicode rules.

•

Trim and its relatives remove only the ASCII space, tab, carriage return and newline. A no-break space (U+00A0), common in text pasted from the web, stays.

•

A str ends at its first zero byte, so binary data passed through these functions is cut short there.

•

Every function that returns a string returns a new one; the argument is never changed.

Making a URL slug from a title

A slug is the readable part of a URL, such as /blog/hello-world. To build one, lower the case, keep letters and digits, and turn every run of anything else into a single dash. Working on code points with CodePoints and IsAlnum keeps letters of every script, so a Persian title gives a Persian slug instead of an empty one.

str-guide-slug.salam
import str

func slug(title: str): str:
    mut b := str.NewBuilder()
    defer str.BufFree(b)
    cps := str.CodePoints(str.Lower(str.Trim(title)))
    defer cps.Free()
    mut dash := false
    each cp in cps:
        if str.IsAlnum(cp):
            if dash and not str.BufIsEmpty(b):
                str.BufAppend(b, "-")
            end
            str.BufAppendCp(b, cp)
            dash = false
        else:
            dash = true
        end
    end
    ret str.BufStr(b)
end

func main:
    println slug("Hello, World!")
    println slug("  10 Tips for Faster   Builds ")
    println slug("Salam 0.5: what's new?")
    println slug("سلام دنیا، به سلام خوش آمدید")
end
Output
hello-world
10-tips-for-faster-builds
salam-0-5-what-s-new
سلام-دنیا-به-سلام-خوش-آمدید

The StringBuilder collects the result without making a new string for every character; BufAppendCp adds one code point as UTF-8 and BufStr returns the finished text. One thing to watch in Persian text: the zero width non-joiner (U+200C) inside a word such as می‌شود is not a letter, so this function would split the word there. If you want to keep it, treat 8204 like a letter in the test.

Counting words

Fields splits on any run of whitespace and drops empty pieces, which is what you want for words; Split with " " would give an empty word for every double space. Lower the case first and turn punctuation into spaces, then count with a HashMap. A separate vector remembers the order in which words first appeared, since a map has no order of its own.

str-guide-words.salam
import str

func main:
    text := "The cat sat. The dog sat too, and the cat ran!"
    clean := str.Replace(str.Replace(str.Replace(str.Lower(text), ".", " "), ",", " "), "!", " ")
    words := str.Fields(clean)
    defer words.Free()
    mut counts := HashMap {} as HashMap<str, int>
    defer counts.Free()
    mut order := Vector {} as Vector<str>
    defer order.Free()
    each w in words:
        if counts.Has(w):
            counts.Put(w, counts.Get(w) + 1)
        else:
            counts.Put(w, 1)
            order.Push(w)
        end
    end
    println words.Len(), "words,", order.Len(), "different"
    each w in order:
        if counts.Get(w) > 1:
            println w, counts.Get(w)
        end
    end
end
Output
11 words, 7 different
the 3
cat 2
sat 2

Each Replace returns a new string. For a long list of characters to remove, one pass over CodePoints with IsPunct is cleaner than a chain of replacements. For Persian text, run it through arabic.SearchKey first so different spellings of the same word count together.

Building CSV with a StringBuilder

Every field that holds a comma, a quote or a line break has to be wrapped in quotes, with each quote inside it doubled. Contains decides whether a field needs that and Replace doubles the quotes. A StringBuilder collects the rows, which is much faster than + once the text grows to thousands of lines.

str-guide-csv.salam
import str

func csv_field(s: str): str:
    if str.Contains(s, ",") or str.Contains(s, "\"") or str.Contains(s, "\n"):
        ret "\"" + str.Replace(s, "\"", "\"\"") + "\""
    end
    ret s
end

func add_row(b &: str.StringBuilder, cells: str[]):
    each i, c in cells:
        if i > 0:
            str.BufAppend(b, ",")
        end
        str.BufAppend(b, csv_field(c))
    end
    str.BufAppend(b, "\n")
end

func main:
    mut b := str.NewBuilder()
    defer str.BufFree(b)
    add_row(b, ["name", "city", "note"])
    add_row(b, ["Ali", "Tehran", "likes tea"])
    add_row(b, ["Sara", "Shiraz, Fars", "said \"hi\""])
    print str.BufStr(b)
end
Output
name,city,note
Ali,Tehran,likes tea
Sara,"Shiraz, Fars","said ""hi"""

The builder is passed with &: so that add_row appends to the caller's builder instead of a copy. Free it once with BufFree when you are done. For reading CSV back, or for files with unusual quoting, use encoding.csv.

Parsing chat commands

A bot or a console reads lines such as /say good morning. Trim removes the stray spaces around the line, StartsWith tells a command from a plain message, and IndexOf finds the first space that separates the command from its argument. EqualFold compares without caring about upper or lower case, so /HELP and /help do the same thing.

str-guide-commands.salam
import str

func handle(line: str): str:
    text := str.Trim(line)
    if not str.StartsWith(text, "/"):
        ret "chat: " + text
    end
    space := str.IndexOf(text, " ")
    mut name := text
    mut rest := ""
    if space > 0:
        name = str.Substr(text, 0, space)
        rest = str.Trim(str.Substr(text, space + 1, text.Len() - space - 1))
    end
    if str.EqualFold(name, "/help"):
        ret "commands: /help, /say TEXT, /shout TEXT"
    else str.EqualFold(name, "/say"):
        ret "bot says: " + rest
    else str.EqualFold(name, "/shout"):
        ret "bot shouts: " + str.Upper(rest)
    end
    ret "unknown command " + str.TrimPrefix(name, "/")
end

func main:
    each line in ["hello everyone", "/HELP", "  /say good morning ", "/Shout fire drill", "/dance"]:
        println handle(line)
    end
end
Output
chat: hello everyone
commands: /help, /say TEXT, /shout TEXT
bot says: good morning
bot shouts: FIRE DRILL
unknown command dance

IndexOf and Substr count in bytes. That is safe here because the space being searched for is a single byte, so the cut always lands on a character boundary even when the argument is Persian. When the position comes from counting characters instead, use CharFind and CharSubstr.

Prefix, suffix, contains

Three questions come up constantly: does the text start with something, end with something, or contain something? The methods s.starts_with(p), s.ends_with(p) and s.includes(sub) answer them with a plain true or false and need no import. StartsWith, EndsWith and Contains in this package are the same checks as functions, which is handy when you want to pass one along. Prefer the methods in new code.

The edge cases are the same everywhere. An empty prefix, suffix or substring always matches, a prefix longer than the text never does, and the comparison is by bytes, so it is case sensitive and a Persian word matches only when every letter does. A string ends at its first zero byte, so for binary data use StartsWithBytes and EndsWithBytes, which take a pointer and a length.

When you also need the rest of the text, CutPrefix and CutSuffix return it and set an ok flag, so you do not check and then cut by hand. For several candidates at once there are StartsWithAny and EndsWithAny, and for URL schemes, header names and file extensions that may come in any case there are StartsWithFold and EndsWithFold.

str-guide-affix.salam
import str

func describe(url: str): str:
    mut schemes := Vector {} as Vector<str>
    schemes.Push("http://")
    schemes.Push("https://")
    if not str.StartsWithAny(url, schemes):
        ret url + ": not a web address"
    end
    mut ok := false
    rest := str.CutPrefix(url, "https://", ok)
    secure := ok
    host := str.CutPrefix(rest, "http://", ok)
    mut kind := "page"
    if host.EndsWith(".png") or host.EndsWith(".jpg"):
        kind = "image"
    end
    if host.Includes("?"):
        kind += " with a query"
    end
    mut label := "plain"
    if secure:
        label = "secure"
    end
    ret label + " " + kind + " at " + host
end

func main:
    each url in [
        "https://salamlang.ir/logo.png", "http://example.org/a?x=1", "ftp://example.org/file",
        "HTTPS://Example.org"
    ]:
        println describe(url)
    end
    println str.StartsWithFold("HTTPS://Example.org", "https://")
    println str.EndsWithFold("Photo.JPG", ".jpg")
end
Output
secure image at salamlang.ir/logo.png
plain page with a query at example.org/a?x=1
ftp://example.org/file: not a web address
HTTPS://Example.org: not a web address
true
true

The last two lines show the fold versions: HTTPS:// and .JPG match even though they are written in capitals. The check on the web address above rejects HTTPS://Example.org because StartsWithAny is exact; switch to a fold check if you want it accepted.

Which function for which job

JobFunctions
Find textContains, StartsWith, EndsWith, IndexOf, LastIndex, Count
Start, end or contain, with or without casestarts_with, ends_with, includes, StartsWithFold, EndsWithFold, StartsWithAny, EndsWithAny
Cut textSubstr (bytes), CharSubstr (characters), Trim, TrimPrefix, TrimSuffix, CutPrefix, CutSuffix
Break into pieces and join againSplit, Fields, Join
Compare ignoring caseEqualFold, CompareFold
Change caseUpper, Lower, Title
Persian, Arabic and English digitsToEnglishDigits, ToPersianDigits, HasPersianDigits
Look at each characterCodePoints, Chars, IsAlnum, IsSpace, IsPunct
Build a long stringNewBuilder, BufAppend, BufStr, BufFree
Compare text that may be written in different Unicode formsNFC, NFD, NFKC

Types

StringBuilder

#
struct StringBuilder

A string builder: the memory in which you build a string piece by piece. Always create one with NewBuilder and use it through the Buf functions; do not change its fields directly.

NameTypeDescription
datavoid*The address of the memory the text is written into.
leni64 = 0How many bytes have been written so far.
capi64 = 0The size of the memory taken, in bytes. It grows by itself when it fills up.
str-StringBuilder.salam
import str

func main:
    mut b := str.NewBuilder()
    defer str.BufFree(b)
    println str.BufIsEmpty(b)
    repeat 1 to 3 in i:
        str.BufAppend(b, "part ")
        str.BufAppendInt(b, i)
        str.BufAppendChar(b, 44)
    end
    str.BufAppendCp(b, 1776)
    println str.BufStr(b)
    println str.BufLen(b), str.BufIsEmpty(b)
    str.BufReset(b)
    println str.BufLen(b)
end
Output
true
part 1,part 2,part 3,۰
23 false
0

Functions

Upper

#
func Upper(s: str): str

Converts the ASCII letters a to z to upper case. Everything else, accented and non-Latin letters included, is left alone, so "café" becomes "CAFé".

str-Upper.salam
import str

func main:
    println str.Upper("salam"), str.Lower("SALAM"), str.Title("hello world")
    println str.EqualFold("Straße", "STRASSE")
    println str.CompareFold("abc", "ABX")
    println str.Upper("سلام")
end
Output
SALAM salam Hello World
true
-21
سلام

Lower

#
func Lower(s: str): str

Converts the ASCII letters A to Z to lower case and leaves every other character alone.

The example for this item is shown with the ones above: str-Upper.salam

Title

#
func Title(s: str): str

Capitalises the first letter of every word and lowers the rest, using the Unicode case tables, so "élan VITAL" becomes "Élan Vital". Words are separated by whitespace only.

The example for this item is shown with the ones above: str-Upper.salam

EqualFold

#
func EqualFold(a: str, b: str): bool

Compares two strings ignoring letter case, following the full Unicode rules, so that "Straße" equals "STRASSE".

The example for this item is shown with the ones above: str-Upper.salam

CompareFold

#
func CompareFold(a: str, b: str): int

Compares two strings ignoring letter case and returns a negative number, zero or a positive one; only the sign matters, not the size.

The example for this item is shown with the ones above: str-Upper.salam

StartsWithFold

#
func StartsWithFold(s: str, prefix: str): bool

Like StartsWith, but ignoring letter case by the full Unicode rules, the same ones EqualFold uses. Use it for things like URL schemes and header names.

str-Affix.salam
import str

func main:
    name := "Report-2026.TXT"
    println name.StartsWith("Report"), name.EndsWith(".txt"), name.Includes("2026")
    println str.StartsWithFold(name, "report"), str.EndsWithFold(name, ".txt")
    mut exts := Vector {} as Vector<str>
    exts.Push(".csv")
    exts.Push(".TXT")
    println str.EndsWithAny(name, exts), str.StartsWithAny(name, exts)
    mut ok := false
    println str.CutPrefix(name, "Report-", ok), ok
    println str.CutSuffix(name, ".md", ok), ok
end
Output
true false true
true true
true false
2026.TXT true
Report-2026.TXT false

EndsWithFold

#
func EndsWithFold(s: str, suffix: str): bool

Like EndsWith, but ignoring letter case by the full Unicode rules. EndsWithFold(name, ".jpg") accepts PHOTO.JPG.

The example for this item is shown with the ones above: str-Affix.salam

Len

#
func Len(s: str): int

Returns the length of the string in bytes. For the number of characters see CharCount.

str-Len.salam
import str

func main:
    a := "apple"
    b := "pear"
    println str.Len(a), str.IsEmpty(""), str.IsEmpty(a)
    println str.Concat(a, b)
    println str.Compare(a, b), str.Compare(b, a), str.Compare(a, "apple")
    println str.Equals(a, "apple")
    println str.Substr("salam donya", 6, 5), str.SubstrIn("salam", 3, 10)
    println str.Find("salam donya", "donya")
    c := str.Clone(a)
    println c
end
Output
5 true false
applepear
-1 1 0
true
donya am
6
apple

ByteLen

#
func ByteLen(s: str): int

Returns the length of the string in bytes and gives the same answer on every backend. On the JavaScript backend Len counts UTF-16 units, so use this one for byte-level work.

str-ByteLen.salam
import str

func main:
    s := "سلام"
    println str.ByteLen(s), str.CharCount(s)
    println str.ByteSub(s, 0, 4)
    println str.CharSubstr(s, 0, 2)
end
Output
8 4
سل
سل

ByteSub

#
func ByteSub(s: str, start: int, n: int): str

Cuts n bytes starting at byte start. The C and LLVM backends return the bytes untouched, but the JavaScript backend decodes them as UTF-8, so a cut that falls inside a multi-byte character produces a replacement character and a different byte length. For cutting by character use CharSubstr.

The example for this item is shown with the ones above: str-ByteLen.salam

Concat

#
func Concat(a: str, b: str): str

Joins two strings one after the other; the same thing + does.

The example for this item is shown with the ones above: str-Len.salam

Compare

#
func Compare(a: str, b: str): int

Compares two strings byte by byte: minus one when the first comes earlier, zero when they are equal and one when it comes later. It is what you want for sorting strings.

The example for this item is shown with the ones above: str-Len.salam

Equals

#
func Equals(a: str, b: str): bool

True when the two strings are exactly the same; the same thing == does.

The example for this item is shown with the ones above: str-Len.salam

Substr

#
func Substr(s: str, start: int, n: int): str

Cuts n bytes starting at byte start. Outside ASCII, take care not to cut through the middle of a character, or use CharSubstr instead.

The example for this item is shown with the ones above: str-Len.salam

SubstrIn

#
func SubstrIn(s: str, start: int, n: int): str

Like Substr, but when the range runs past the end of the string it does not fail and returns only the part that is there.

The example for this item is shown with the ones above: str-Len.salam

Find

#
func Find(s: str, sub: str): int

Returns the position of the first occurrence of sub in bytes, or minus one.

The example for this item is shown with the ones above: str-Len.salam

Split

#
func Split(s: str, delim: str): Vector<str>

Splits the string wherever delim occurs and returns the pieces in a vector. Free the vector when you are done with it.

str-Split.salam
import str

func main:
    parts := str.Split("apple,pear,grape", ",")
    defer parts.Free()
    println parts.Len(), parts.Get(1)
    println str.Join(parts, " / ")
end
Output
3 pear
apple / pear / grape

Join

#
func Join(parts: Vector<str>, sep: str): str

Joins the pieces of a vector with sep between them; the reverse of Split.

The example for this item is shown with the ones above: str-Split.salam

Trim

#
func Trim(s: str): str

Removes spaces, tabs, carriage returns and newlines at both ends. Use it on user input before anything else. Other Unicode spaces, such as the no-break space, are kept.

str-Trim.salam
import str

func main:
    s := "   hello world   "
    println "[" + str.Trim(s) + "]"
    println "[" + str.TrimLeft(s) + "]"
    println "[" + str.TrimRight(s) + "]"
    println str.TrimPrefix("https://salamlang.ir", "https://")
    println str.TrimSuffix("report.txt", ".txt")
end
Output
[hello world]
[hello world   ]
[   hello world]
salamlang.ir
report

ToInt

#
func ToInt(s: str): int

Turns the string into a whole number, accepting Persian and Arabic digits too. When it finds no number it returns zero.

str-ToInt.salam
import str

func main:
    println str.ToInt("42") + 1, str.ToInt("abc")
    println str.ToFloat("2.5") * 2
    println "[" + str.FromInt(-15) + "]", "[" + str.FromFloat(1.25) + "]"
end
Output
43 0
5
[-15] [1.25]

ToFloat

#
func ToFloat(s: str): f64

Turns the string into a decimal number.

The example for this item is shown with the ones above: str-ToInt.salam

IsEmpty

#
func IsEmpty(s: str): bool

True when the string has no characters at all.

The example for this item is shown with the ones above: str-Len.salam

Clone

#
func Clone(s: str): str

Makes an independent copy of the string.

The example for this item is shown with the ones above: str-Len.salam

Replace

#
func Replace(s: str, find: str, replacement: str): str

Replaces every occurrence of find with replacement.

str-Replace.salam
import str

func main:
    println str.Replace("I like apples, red apples", "apple", "pear")
end
Output
I like pears, red pears

FromInt

#
func FromInt(i: i64): str

Turns a whole number into text.

The example for this item is shown with the ones above: str-ToInt.salam

FromFloat

#
func FromFloat(f: f64): str

Turns a decimal number into text.

The example for this item is shown with the ones above: str-ToInt.salam

CodePointAt

#
func CodePointAt(s: str, i: int, cp &: int): int

Reads the character starting at byte i, puts its code point in cp and returns how many bytes it took. For walking a string by hand, character by character.

str-CharCount.salam
import str

func main:
    s := "سلام"
    println str.Len(s), str.CharCount(s)
    println str.CharAtIndex(s, 1), str.CharSubstr(s, 1, 2)
    println str.CharFind(s, "ام"), str.Reverse(s)
    println str.CharAt(s, 2)
    mut code := 0
    width := str.CodePointAt(s, 0, code)
    println code, width, str.CharLen(216)
    points := str.CodePoints(s)
    println points
    println str.FromCodePoints(points)
    println str.Chars("ab۱")
    println str.AllAscii("salam"), str.AllAscii("سلام")
end
Output
8 4
ل لا
2 مالس
ل
1587 2 2
[1587, 1604, 1575, 1605]
سلام
["a", "b", "۱"]
true false

CharLen

#
func CharLen(lead: int): int

From the first byte of a character, says how many bytes that character takes, from 1 to 4.

The example for this item is shown with the ones above: str-CharCount.salam

CharAt

#
func CharAt(s: str, i: int): str

Returns the character starting at byte i. That is a byte position, not a character position; for a character position see CharAtIndex.

The example for this item is shown with the ones above: str-CharCount.salam

Reverse

#
func Reverse(s: str): str

Reverses the order of the characters in the string. If the text carries marks or emoji, ReverseGraphemes is the correct one.

The example for this item is shown with the ones above: str-CharCount.salam

CharCount

#
func CharCount(s: str): int

Returns the number of characters in the string rather than bytes. For "سلام" it is four, while Len says eight.

The example for this item is shown with the ones above: str-CharCount.salam

CharSubstr

#
func CharSubstr(s: str, start: int, n: int): str

Cuts n characters starting at character start. It is the safe version of Substr for text outside ASCII.

The example for this item is shown with the ones above: str-CharCount.salam

CharAtIndex

#
func CharAtIndex(s: str, i: int): str

Returns character number i, counting from zero.

The example for this item is shown with the ones above: str-CharCount.salam

CharFind

#
func CharFind(s: str, sub: str): int

Returns the position of the first occurrence of sub in characters, or minus one when it is not there.

The example for this item is shown with the ones above: str-CharCount.salam

CodePoints

#
func CodePoints(s: str): Vector<int>

Returns the code points of every character in the string, in a vector.

The example for this item is shown with the ones above: str-CharCount.salam

FromCodePoints

#
func FromCodePoints(cps: Vector<int>): str

The reverse of CodePoints: builds a string from a vector of code points.

The example for this item is shown with the ones above: str-CharCount.salam

AllAscii

#
func AllAscii(s: str): bool

True when every character in the string is ASCII. Useful for choosing a faster path when processing text.

The example for this item is shown with the ones above: str-CharCount.salam

Chars

#
func Chars(s: str): Vector<str>

Returns each character of the string as a separate string in a vector.

The example for this item is shown with the ones above: str-CharCount.salam

Contains

#
func Contains(s: str, sub: str): bool

True when sub occurs anywhere in the string.

str-Contains.salam
import str

func main:
    s := "salam, salam world"
    println str.Contains(s, "world"), str.StartsWith(s, "salam"), str.EndsWith(s, "world")
    println str.IndexOf(s, "salam"), str.LastIndex(s, "salam"), str.Search(s, "missing")
    println str.IndexFrom(s, "salam", 1), str.Count(s, "salam")
end
Output
true true true
0 7 -1
7 2

StartsWith

#
func StartsWith(s: str, prefix: str): bool

True when the string starts with prefix.

The example for this item is shown with the ones above: str-Contains.salam

EndsWith

#
func EndsWith(s: str, suffix: str): bool

True when the string ends with suffix.

The example for this item is shown with the ones above: str-Contains.salam

Search

#
func Search(s: str, sub: str): int

Returns the position of the first occurrence of sub in bytes, or minus one. It is the same as IndexOf.

The example for this item is shown with the ones above: str-Contains.salam

IndexOf

#
func IndexOf(s: str, sub: str): int

Returns the position of the first occurrence of sub in bytes, or minus one when it is not found.

The example for this item is shown with the ones above: str-Contains.salam

IndexFrom

#
func IndexFrom(s: str, sub: str, from: int): int

Like IndexOf, but starts the search at byte from, for finding the next occurrence.

The example for this item is shown with the ones above: str-Contains.salam

Count

#
func Count(s: str, sub: str): int

Returns the number of non-overlapping occurrences of sub in the string.

The example for this item is shown with the ones above: str-Contains.salam

LastIndex

#
func LastIndex(s: str, sub: str): int

Returns the position of the last occurrence of sub in bytes, or minus one.

The example for this item is shown with the ones above: str-Contains.salam

StartsWithAny

#
func StartsWithAny(s: str, prefixes: Vector<str>): bool

True when the string starts with at least one of the prefixes in the vector. An empty vector gives false; an empty prefix in it matches everything.

The example for this item is shown with the ones above: str-Affix.salam

EndsWithAny

#
func EndsWithAny(s: str, suffixes: Vector<str>): bool

True when the string ends with at least one of the suffixes in the vector. Handy for a list of file extensions.

The example for this item is shown with the ones above: str-Affix.salam

CutPrefix

#
func CutPrefix(s: str, prefix: str, ok &: bool): str

If the string starts with prefix, returns the rest and sets ok to true; otherwise returns a copy of the string and sets ok to false. Unlike TrimPrefix it tells you whether anything was removed.

The example for this item is shown with the ones above: str-Affix.salam

CutSuffix

#
func CutSuffix(s: str, suffix: str, ok &: bool): str

If the string ends with suffix, returns the part before it and sets ok to true; otherwise returns a copy of the string and sets ok to false.

The example for this item is shown with the ones above: str-Affix.salam

StartsWithBytes

#
func StartsWithBytes(data: void*, n: int, prefix: void*, m: int): bool

Checks the first bytes of a buffer against a prefix, both given as a pointer and a length, so zero bytes are compared like any other byte. Use it for binary data that a str cannot hold.

str-AffixBytes.salam
import str
import mem

func main:
    data := mem.MustAllocateZeroed(6 as u64) as i8*
    mark := mem.MustAllocateZeroed(3 as u64) as i8*
    data[0] = 80 as i8
    data[1] = 75 as i8
    data[2] = 0 as i8
    data[3] = 1 as i8
    data[4] = 2 as i8
    mark[0] = 0 as i8
    mark[1] = 1 as i8
    mark[2] = 2 as i8
    println str.StartsWithBytes(data as void*, 5, data as void*, 2)
    println str.StartsWithBytes(data as void*, 1, data as void*, 2)
    println str.EndsWithBytes(data as void*, 5, mark as void*, 3)
    println str.EndsWithBytes(data as void*, 2, mark as void*, 3)
    mem.Free(data as void*)
    mem.Free(mark as void*)
end
Output
true
false
true
false

EndsWithBytes

#
func EndsWithBytes(data: void*, n: int, suffix: void*, m: int): bool

Checks the last bytes of a buffer against a suffix, both given as a pointer and a length. A negative or too long suffix gives false.

The example for this item is shown with the ones above: str-AffixBytes.salam

TrimLeft

#
func TrimLeft(s: str): str

Removes the spaces, tabs and newlines at the start of the string.

The example for this item is shown with the ones above: str-Trim.salam

TrimRight

#
func TrimRight(s: str): str

Removes the spaces, tabs and newlines at the end of the string.

The example for this item is shown with the ones above: str-Trim.salam

TrimPrefix

#
func TrimPrefix(s: str, prefix: str): str

If the string starts with prefix, removes it; otherwise returns the string untouched.

The example for this item is shown with the ones above: str-Trim.salam

TrimSuffix

#
func TrimSuffix(s: str, suffix: str): str

If the string ends with suffix, removes it; handy for stripping a file extension.

The example for this item is shown with the ones above: str-Trim.salam

DigitValue

#
func DigitValue(cp: int): int

Returns the numeric value of a digit, whether it is written in English, Persian or Arabic digits. For a character that is not a digit it returns minus one.

str-Digits.salam
import str

func main:
    println str.ToPersianDigits("order 1403")
    println str.ToEnglishDigits("code ۱۲۳ and ٤٥٦")
    println str.ToArabicDigits("2025")
    println str.HasPersianDigits("۱۲"), str.HasArabicDigits("۱۲"), str.HasEnglishDigits("12")
    d := str.CodePoints("۷").Get(0)
    println str.IsPersianDigit(d), str.IsArabicDigit(d), str.IsAnyDigit(d)
    println str.DigitValue(d), str.DigitValue(65)
end
Output
order ۱۴۰۳
code 123 and 456
٢٠٢٥
true false true
true false true
7 -1

IsArabicDigit

#
func IsArabicDigit(cp: int): bool

True when the character is one of the Arabic digits ٠ to ٩. Persian digits have a different shape and do not count here.

The example for this item is shown with the ones above: str-Digits.salam

IsPersianDigit

#
func IsPersianDigit(cp: int): bool

True when the character is one of the Persian digits ۰ to ۹.

The example for this item is shown with the ones above: str-Digits.salam

IsAnyDigit

#
func IsAnyDigit(cp: int): bool

True when the character is an English, Persian or Arabic digit. Use this to accept a number from a user with any keyboard.

The example for this item is shown with the ones above: str-Digits.salam

ToEnglishDigits

#
func ToEnglishDigits(s: str): str

Converts every Persian and Arabic digit in the string to an English one and leaves the rest of the text alone. Useful before storing a phone number or an identifier in a database.

The example for this item is shown with the ones above: str-Digits.salam

ToArabicDigits

#
func ToArabicDigits(s: str): str

Converts every digit in the string to an Arabic one.

The example for this item is shown with the ones above: str-Digits.salam

ToPersianDigits

#
func ToPersianDigits(s: str): str

Converts every digit in the string to a Persian one, for showing a number to a Persian-speaking reader.

The example for this item is shown with the ones above: str-Digits.salam

HasEnglishDigits

#
func HasEnglishDigits(s: str): bool

True when the string contains at least one English digit.

The example for this item is shown with the ones above: str-Digits.salam

HasArabicDigits

#
func HasArabicDigits(s: str): bool

True when the string contains at least one Arabic digit.

The example for this item is shown with the ones above: str-Digits.salam

HasPersianDigits

#
func HasPersianDigits(s: str): bool

True when the string contains at least one Persian digit.

The example for this item is shown with the ones above: str-Digits.salam

IsAscii

#
func IsAscii(code: int): bool

True when the code is in the ASCII range, zero to 127.

str-IsAscii.salam
import str

func main:
    each s in ["A", "z", "7", " ", "!", "ب", "۷", "\t"]:
        c := str.CodePoints(s).Get(0)
        println "[" + s + "]",
            str.IsAscii(c),
            str.IsAlpha(c),
            str.IsDigit(c),
            str.IsSpace(c),
            str.IsPunct(c)
    end
    println str.IsAsciiUpper(65), str.IsAsciiLower(65), str.IsUpper(1040), str.IsLower(1072)
    println str.IsAsciiDigit(50), str.IsAsciiAlpha(50), str.IsAsciiAlnum(50), str.IsAsciiSpace(32)
    println str.IsAlnum(1776), str.IsMark(1614), str.IsControl(10)
end
Output
[A] true true false false false
[z] true true false false false
[7] true false true false false
[ ] true false false true false
[!] true false false false true
[ب] false true false false false
[۷] false false true false false
[	] true false false true false
true false true true
true false true true
true true true

IsAsciiSpace

#
func IsAsciiSpace(code: int): bool

Only ASCII whitespace: space, tab, newline and the like.

The example for this item is shown with the ones above: str-IsAscii.salam

IsAsciiDigit

#
func IsAsciiDigit(code: int): bool

Only the English digits 0 to 9.

The example for this item is shown with the ones above: str-IsAscii.salam

IsAsciiUpper

#
func IsAsciiUpper(code: int): bool

Only the capital English letters A to Z.

The example for this item is shown with the ones above: str-IsAscii.salam

IsAsciiLower

#
func IsAsciiLower(code: int): bool

Only the small English letters a to z.

The example for this item is shown with the ones above: str-IsAscii.salam

IsAsciiAlpha

#
func IsAsciiAlpha(code: int): bool

Only English letters, capital or small.

The example for this item is shown with the ones above: str-IsAscii.salam

IsAsciiAlnum

#
func IsAsciiAlnum(code: int): bool

An English letter or digit.

The example for this item is shown with the ones above: str-IsAscii.salam

IsSpace

#
func IsSpace(code: int): bool

Any Unicode whitespace, including the ASCII spaces and the ideographic space.

The example for this item is shown with the ones above: str-IsAscii.salam

IsDigit

#
func IsDigit(code: int): bool

Any Unicode decimal digit, Persian and Arabic included.

The example for this item is shown with the ones above: str-IsAscii.salam

IsUpper

#
func IsUpper(code: int): bool

A capital letter in any script that has them, such as Latin, Greek and Cyrillic.

The example for this item is shown with the ones above: str-IsAscii.salam

IsLower

#
func IsLower(code: int): bool

A small letter in any script that has them.

The example for this item is shown with the ones above: str-IsAscii.salam

IsAlpha

#
func IsAlpha(code: int): bool

Any letter in any script.

The example for this item is shown with the ones above: str-IsAscii.salam

IsAlnum

#
func IsAlnum(code: int): bool

Any letter or digit in any script.

The example for this item is shown with the ones above: str-IsAscii.salam

IsPunct

#
func IsPunct(code: int): bool

Any punctuation mark, such as a full stop, a comma or a question mark.

The example for this item is shown with the ones above: str-IsAscii.salam

IsMark

#
func IsMark(code: int): bool

A combining mark, such as an accent or an Arabic vowel sign.

The example for this item is shown with the ones above: str-IsAscii.salam

IsControl

#
func IsControl(code: int): bool

A control character such as a newline or a tab: invisible, and doing something rather than showing something.

The example for this item is shown with the ones above: str-IsAscii.salam

GraphemeCount

#
func GraphemeCount(s: str): int

Returns the number of grapheme clusters, that is, the number of "letters" a reader sees.

str-Graphemes.salam
import str

func main:
    s := "کَتاب👨‍👩‍👧"
    println str.CharCount(s), str.GraphemeCount(s)
    println str.Graphemes(s)
    println str.ReverseGraphemes("سَلام")
end
Output
10 5
["کَ", "ت", "ا", "ب", "👨‍👩‍👧"]
مالسَ

Graphemes

#
func Graphemes(s: str): Vector<str>

Splits the string into grapheme clusters: a letter with its marks, or a composed emoji, is one piece.

The example for this item is shown with the ones above: str-Graphemes.salam

ReverseGraphemes

#
func ReverseGraphemes(s: str): str

Reverses the string cluster by cluster, so that marks stay attached to their letter.

The example for this item is shown with the ones above: str-Graphemes.salam

Repeat

#
func Repeat(s: str, n: int): str

Repeats the string n times, one after another; good for drawing a separator line.

str-Fields.salam
import str

func main:
    println str.Repeat("=-", 5)
    words := str.Fields("  the Salam   programming\tlanguage \n")
    println words.Len(), words
end
Output
=-=-=-=-=-
4 ["the", "Salam", "programming", "language"]

Fields

#
func Fields(s: str): Vector<str>

Splits the string into words on any run of spaces, tabs or newlines, dropping the empty pieces.

The example for this item is shown with the ones above: str-Fields.salam

NewBuilder

#
func NewBuilder(): StringBuilder

Creates an empty string builder. When you are building a long piece of text in parts, this is far faster than joining with + over and over. Release it with BufFree when you are done.

The example for this item is shown with the ones above: str-StringBuilder.salam

BufAppend

#
func BufAppend(b &: StringBuilder, s: str)

Adds a string to the end of the builder.

The example for this item is shown with the ones above: str-StringBuilder.salam

BufAppendChar

#
func BufAppendChar(b &: StringBuilder, code: int)

Adds one byte by its numeric code, for ASCII characters such as a comma (44).

The example for this item is shown with the ones above: str-StringBuilder.salam

BufAppendCp

#
func BufAppendCp(b &: StringBuilder, cp: int)

Adds one Unicode character by its code point, for anything outside ASCII.

The example for this item is shown with the ones above: str-StringBuilder.salam

BufAppendInt

#
func BufAppendInt(b &: StringBuilder, n: i64)

Adds a whole number in its text form.

The example for this item is shown with the ones above: str-StringBuilder.salam

BufLen

#
func BufLen(b &: StringBuilder): i64

Returns the size of the text built so far, in bytes.

The example for this item is shown with the ones above: str-StringBuilder.salam

BufIsEmpty

#
func BufIsEmpty(b &: StringBuilder): bool

True when nothing has been added to the builder yet.

The example for this item is shown with the ones above: str-StringBuilder.salam

BufStr

#
func BufStr(b &: StringBuilder): str

Returns the text built so far as a fresh string. The builder stays usable afterwards.

The example for this item is shown with the ones above: str-StringBuilder.salam

BufReset

#
func BufReset(b &: StringBuilder)

Empties the builder but keeps its memory, so it can be reused for the next piece of text.

The example for this item is shown with the ones above: str-StringBuilder.salam

BufFree

#
func BufFree(b &: StringBuilder)

Releases the builder's memory. The best place for it is a defer right after creating the builder.

The example for this item is shown with the ones above: str-StringBuilder.salam

NFD

#
func NFD(s: str): str

Converts the string to Unicode "canonical decomposition": every composed character is split into its base and its marks.

str-NFC.salam
import str

func main:
    composed := "آ"
    decomposed := str.NFD(composed)
    println composed.Len(), decomposed.Len(), composed == decomposed
    println str.NFC(decomposed) == composed
    println str.IsNFC(composed), str.IsNFC(decomposed)
    presentation := "ﻼ"
    println str.NFKD(presentation), str.NFKC(presentation)
end
Output
2 4 false
true
true false
لا لا

NFC

#
func NFC(s: str): str

Converts the string to "canonical composition": bases and marks are recombined into single characters wherever possible. Two strings that look identical but are stored with different codes become equal after this, so apply it before comparing or storing.

The example for this item is shown with the ones above: str-NFC.salam

NFKD

#
func NFKD(s: str): str

Like canonical decomposition, but it also expands the "compatibility" forms; Arabic presentation forms such as ﻻ, for instance, become ordinary letters.

The example for this item is shown with the ones above: str-NFC.salam

NFKC

#
func NFKC(s: str): str

Compatibility decomposition followed by canonical composition. It suits text gathered from mixed sources, such as PDFs.

The example for this item is shown with the ones above: str-NFC.salam

IsNFC

#
func IsNFC(s: str): bool

True when the string is already in canonical composition. The check is cheaper than the conversion.

The example for this item is shown with the ones above: str-NFC.salam