Everything to do with text: searching, slicing, replacing, digits, case, and building long strings.
importstr
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
importstrfuncslug(title: str): str:
mut b := str.NewBuilder()
deferstr.BufFree(b)
cps := str.CodePoints(str.Lower(str.Trim(title)))
defer cps.Free()
mut dash := falseeach cp in cps:
ifstr.IsAlnum(cp):
if dash andnotstr.BufIsEmpty(b):
str.BufAppend(b, "-")
endstr.BufAppendCp(b, cp)
dash = falseelse:
dash = trueendendretstr.BufStr(b)
endfuncmain:
printlnslug("Hello, World!")
printlnslug(" 10 Tips for Faster Builds ")
printlnslug("Salam 0.5: what's new?")
printlnslug("سلام دنیا، به سلام خوش آمدید")
end
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
importstrfuncmain:
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 {} asHashMap<str, int>
defer counts.Free()
mut order := Vector {} asVector<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)
endendprintln words.Len(), "words,", order.Len(), "different"each w in order:
if counts.Get(w) > 1:
println w, counts.Get(w)
endendend
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
importstrfunccsv_field(s: str): str:
ifstr.Contains(s, ",") orstr.Contains(s, "\"") orstr.Contains(s, "\n"):
ret"\"" + str.Replace(s, "\"", "\"\"") + "\""endret s
endfuncadd_row(b &: str.StringBuilder, cells: str[]):
each i, c in cells:
if i > 0:
str.BufAppend(b, ",")
endstr.BufAppend(b, csv_field(c))
endstr.BufAppend(b, "\n")
endfuncmain:
mut b := str.NewBuilder()
deferstr.BufFree(b)
add_row(b, ["name", "city", "note"])
add_row(b, ["Ali", "Tehran", "likes tea"])
add_row(b, ["Sara", "Shiraz, Fars", "said \"hi\""])
printstr.BufStr(b)
end
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
importstrfunchandle(line: str): str:
text := str.Trim(line)
ifnotstr.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))
endifstr.EqualFold(name, "/help"):
ret"commands: /help, /say TEXT, /shout TEXT"elsestr.EqualFold(name, "/say"):
ret"bot says: " + rest
elsestr.EqualFold(name, "/shout"):
ret"bot shouts: " + str.Upper(rest)
endret"unknown command " + str.TrimPrefix(name, "/")
endfuncmain:
each line in ["hello everyone", "/HELP", " /say good morning ", "/Shout fire drill", "/dance"]:
printlnhandle(line)
endend
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
importstrfuncdescribe(url: str): str:
mut schemes := Vector {} asVector<str>
schemes.Push("http://")
schemes.Push("https://")
ifnotstr.StartsWithAny(url, schemes):
ret url + ": not a web address"endmut 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"endif host.Includes("?"):
kind += " with a query"endmut label := "plain"if secure:
label = "secure"endret label + " " + kind + " at " + host
endfuncmain:
each url in [
"https://salamlang.ir/logo.png", "http://example.org/a?x=1", "ftp://example.org/file",
"HTTPS://Example.org"
]:
printlndescribe(url)
endprintlnstr.StartsWithFold("HTTPS://Example.org", "https://")
printlnstr.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.
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.
Name
Type
Description
data
void*
The address of the memory the text is written into.
len
i64 = 0
How many bytes have been written so far.
cap
i64 = 0
The size of the memory taken, in bytes. It grows by itself when it fills up.
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
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
importstrfuncmain:
name := "Report-2026.TXT"println name.StartsWith("Report"), name.EndsWith(".txt"), name.Includes("2026")
printlnstr.StartsWithFold(name, "report"), str.EndsWithFold(name, ".txt")
mut exts := Vector {} asVector<str>
exts.Push(".csv")
exts.Push(".TXT")
printlnstr.EndsWithAny(name, exts), str.StartsWithAny(name, exts)
mut ok := falseprintlnstr.CutPrefix(name, "Report-", ok), ok
printlnstr.CutSuffix(name, ".md", ok), ok
end
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
importstrfuncmain:
s := "سلام"printlnstr.ByteLen(s), str.CharCount(s)
printlnstr.ByteSub(s, 0, 4)
printlnstr.CharSubstr(s, 0, 2)
end
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
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
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
importstrfuncmain:
s := " hello world "println"[" + str.Trim(s) + "]"println"[" + str.TrimLeft(s) + "]"println"[" + str.TrimRight(s) + "]"printlnstr.TrimPrefix("https://salamlang.ir", "https://")
printlnstr.TrimSuffix("report.txt", ".txt")
end
Output
[hello world]
[hello world ]
[ hello world]
salamlang.ir
report
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.
funcCutPrefix(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
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
importstrimport mem
funcmain:
data := mem.MustAllocateZeroed(6asu64) asi8*
mark := mem.MustAllocateZeroed(3asu64) asi8*
data[0] = 80asi8
data[1] = 75asi8
data[2] = 0asi8
data[3] = 1asi8
data[4] = 2asi8
mark[0] = 0asi8
mark[1] = 1asi8
mark[2] = 2asi8printlnstr.StartsWithBytes(data asvoid*, 5, data asvoid*, 2)
printlnstr.StartsWithBytes(data asvoid*, 1, data asvoid*, 2)
printlnstr.EndsWithBytes(data asvoid*, 5, mark asvoid*, 3)
printlnstr.EndsWithBytes(data asvoid*, 2, mark asvoid*, 3)
mem.Free(data asvoid*)
mem.Free(mark asvoid*)
end
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
importstrfuncmain:
printlnstr.ToPersianDigits("order 1403")
printlnstr.ToEnglishDigits("code ۱۲۳ and ٤٥٦")
printlnstr.ToArabicDigits("2025")
printlnstr.HasPersianDigits("۱۲"), str.HasArabicDigits("۱۲"), str.HasEnglishDigits("12")
d := str.CodePoints("۷").Get(0)
printlnstr.IsPersianDigit(d), str.IsArabicDigit(d), str.IsAnyDigit(d)
printlnstr.DigitValue(d), str.DigitValue(65)
end
Output
order ۱۴۰۳
code 123 and 456
٢٠٢٥
true false true
true false true
7 -1
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
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.
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
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