strutils
nimony/lib/std/strutils.nim
ASCII-focused helpers for splitting, searching, comparing, replacing, escaping, percent-formatting (%, format), float rendering (formatFloat, formatBiggestFloat), and human-readable sizes (formatSize).
Shared set[char] constants (Whitespace, Letters, …) describe common character classes; see each constant for details.
const Whitespace: set[char]All the characters that count as whitespace (space, tab, vertical tab, carriage return, new line, form feed).
const Letters: set[char]The set of letters.
const UppercaseLetters: set[char]The set of uppercase ASCII letters.
const LowercaseLetters: set[char]The set of lowercase ASCII letters.
const PunctuationChars: set[char]The set of all ASCII punctuation characters.
const Digits: set[char]The set of digits.
const HexDigits: set[char]The set of hexadecimal digits.
const IdentChars: set[char]The set of characters an identifier can consist of.
const IdentStartChars: set[char]The set of characters an identifier can start with.
const Newlines: set[char]The set of characters a newline terminator can start with (carriage return, line feed).
const PrintableChars: set[char]The set of all printable ASCII characters (letters, digits, whitespace, and punctuation characters).
const AllChars: set[char]A set with all the possible characters.
Not very useful by its own, you can use it to create inverted sets to make the
find func<#find,string,set[char],Natural,int>_ find invalid characters in strings. Example:nim let invalid = AllChars - Digits doAssert "01234".find(invalid) == -1 doAssert "01A34".find(invalid) == 2func spaces(n: int64): stringReturns a string with
nspace characters.func repeat(c: char; n: int64): stringReturns a string made of
crepeatedntimes.func repeat(s: string; n: int64): stringReturns
srepeatedntimes.func isAlphaAscii(c: char): boolChecks whether or not character
cis alphabetical.This checks a-z, A-Z ASCII characters only. Use
Unicode module<unicode.html>_ for UTF-8 support.func isAlphaNumeric(c: char): boolChecks whether or not
cis alphanumeric.This checks a-z, A-Z, 0-9 ASCII characters only.
func isDigit(c: char): boolChecks whether or not
cis a number.This checks 0-9 ASCII characters only.
func isSpaceAscii(c: char): boolChecks whether or not
cis a whitespace character.func isLowerAscii(c: char): boolChecks whether or not
cis a lower case character.This checks ASCII characters only. Use
Unicode module<unicode.html>_ for UTF-8 support.See also:
toLowerAscii func<#toLowerAscii,char>_
func isUpperAscii(c: char): boolChecks whether or not
cis an upper case character.This checks ASCII characters only. Use
Unicode module<unicode.html>_ for UTF-8 support.See also:
toUpperAscii func<#toUpperAscii,char>_
func allCharsInSet(s: string; theSet: set[char]): boolReturns true if every character of
sis in the settheSet.func isEmptyOrWhitespace(s: string): boolChecks if
sis empty or consists entirely of whitespace characters.func endsWith(s: string; c: char): boolTrue if
sis non-empty and its last character isc.func strlen(x: cstring): int64Length of the C string
x(not counting the terminating zero). Freestanding (nimony n, libc-free): scan for the NUL terminator directly.func $(x: cstring): stringCopies a nil-terminated C string into a Nim
string.func $(x: char): stringReturns a one-character string containing
x.iterator split(s: string; seps: set[char]; maxsplit: int64): stringSplits the string
sinto substrings using a group of separators.Substrings are separated by a substring containing only
seps.nim for word in split("this\lis an\texample"): writeLine(stdout, word)...generates this output:
"this" "is" "an" "example"And the following code:
nim for word in split("this:is;an$example", {';', ':', '$'}): writeLine(stdout, word)...produces the same output as the first example. The code:
nim let date = "2012-11-20T22:08:08.398990" let separators = {' ', '-', ':', 'T'} for number in split(date, separators): writeLine(stdout, number)...results in:
"2012" "11" "20" "22" "08" "08.398990".. note:: Empty separator set results in returning an original string, following the interpretation "split by no element".
iterator split(s: string; sep: char; maxsplit: int64): stringSplits the string
sinto substrings using the separatorsep.Substrings are separated by the character
sep.iterator split(s: string; sep: string; maxsplit: int64): stringSplits the string
sinto substrings using the separatorsep.iterator splitLines(s: string; keepEol: bool): stringSplits the string
sinto its containing lines. Supports LF, CR, and CR-LF line endings.iterator splitWhitespace(s: string; maxsplit: int64): stringSplits the string
sat whitespace, stripping leading and trailing whitespace and collapsing runs of whitespace (no empty substrings are produced). Ifmaxsplitis positive, at mostmaxsplitsplits are made.nim for word in splitWhitespace(" foo \t bar baz "): writeLine(stdout, word)...generates "foo", "bar", "baz".
func split(s: string; seps: set[char]; maxsplit: int64): seqThe same as the
splititerator, but returns a sequence of substrings.func split(s: string; sep: char; maxsplit: int64): seqThe same as the
splititerator, but returns a sequence of substrings.func split(s: string; sep: string; maxsplit: int64): seqThe same as the
splititerator, but returns a sequence of substrings.func splitLines(s: string; keepEol: bool): seqThe same as the
splitLinesiterator, but returns a sequence of substrings.func splitWhitespace(s: string; maxsplit: int64): seqThe same as the
splitWhitespaceiterator, but returns a sequence of substrings.func join(a: openArray; sep: string): stringConcatenates all strings in
a, separating them withsep.func delete(s: var string; slice: HSlice)Deletes the items
s[slice].This operation moves all elements after
s[slice]in linear time, and is the string analog tosequtils.delete.func continuesWith(s: string; prefix: string; start: int64): boolReturns true if
scontinues withprefixat positionstart.If
prefix == ""true is returned.See also:
startsWith func<#startsWith,string,string>_endsWith func<#endsWith,string,string>_
func startsWith(s: string; prefix: string): boolReturns true if
sstarts with stringprefix.If
prefix == ""true is returned.See also:
endsWith func<#endsWith,string,string>_continuesWith func<#continuesWith,string,string,Natural>_removePrefix func<#removePrefix,string,string>_
func endsWith(s: string; suffix: string): boolReturns true if
sends withsuffix.If
suffix == ""true is returned.See also:
startsWith func<#startsWith,string,string>_continuesWith func<#continuesWith,string,string,Natural>_removeSuffix func<#removeSuffix,string,string>_
func toLowerAscii(c: char): charReturns the lower case version of character
c.This works only for the letters
A-Z. See unicode.toLower for a version that works for any Unicode character.See also:
isLowerAscii func<#isLowerAscii,char>_toLowerAscii func<#toLowerAscii,string>_ for converting a string
func toLowerAscii(s: string): stringConverts string
sinto lower case.This works only for the letters
A-Z. See unicode.toLower for a version that works for any Unicode character.See also:
normalize func<#normalize,string>_
func toUpperAscii(c: char): charConverts character
cinto upper case.This works only for the letters
A-Z. See unicode.toUpper for a version that works for any Unicode character.See also:
isUpperAscii func<#isUpperAscii,char>_toUpperAscii func<#toUpperAscii,string>_ for converting a stringcapitalizeAscii func<#capitalizeAscii,string>_
func toUpperAscii(s: string): stringConverts string
sinto upper case.This works only for the letters
A-Z. See unicode.toUpper for a version that works for any Unicode character.See also:
capitalizeAscii func<#capitalizeAscii,string>_
func capitalizeAscii(s: string): stringConverts the first character of string
sinto upper case.This works only for the letters
A-Z. UseUnicode module<unicode.html>_ for UTF-8 support.See also:
toUpperAscii func<#toUpperAscii,char>_
func normalize(s: string): stringNormalizes the string
s.That means to convert it to lower case and remove any '_'. This should NOT be used to normalize Nim identifier names.
See also:
toLowerAscii func<#toLowerAscii,string>_
func cmpIgnoreCase(a: string; b: string): int64Compares two strings in a case insensitive manner. Returns:
|
0if a == b|
< 0if a < b|
> 0if a > bfunc cmpIgnoreStyle(a: string; b: string): int64Semantically the same as
cmp(normalize(a), normalize(b)). It is just optimized to not allocate temporary strings. This should NOT be used to compare Nim identifier names. Usemacros.eqIdent<macros.html#eqIdent,string,string>_ for that.Returns:
|
0if a == b|
< 0if a < b|
> 0if a > bfunc find(s: string; sub: char; start: int64; last: int64): int64Searches for
subinsinside rangestart..last(both ends included). Iflastis unspecified or negative, it defaults tos.high(the last element).Searching is case-sensitive. If
subis not ins, -1 is returned. Otherwise the index returned is relative tos[0], notstart. Subtractstartfrom the result for astart-origin index.See also:
replace func<#replace,string,char,char>_
func find(s: string; chars: set[char]; start: int64; last: int64): int64Searches for
charsinsinside rangestart..last(both ends included). Iflastis unspecified or negative, it defaults tos.high(the last element).If
scontains none of the characters inchars, -1 is returned. Otherwise the index returned is relative tos[0], notstart. Subtractstartfrom the result for astart-origin index.See also:
multiReplace func<#multiReplace,string,varargs[]>_
type SkipTable = array[0..255, int64]Character table for efficient substring search.
func initSkipTable(a: var array[0..255, int64]; sub: string)Initializes table
afor efficient search of substringsub.See also:
initSkipTable func<#initSkipTable,string>_find func<#find,SkipTable,string,string,Natural,int>_
func initSkipTable(sub: string): array[0..255, int64]Returns a new table initialized for
sub.See also:
initSkipTable func<#initSkipTable,SkipTable,string>_find func<#find,SkipTable,string,string,Natural,int>_
func find(a: array[0..255, int64]; s: string; sub: string; start: int64; last: int64): int64Searches for
subinsinside rangestart..lastusing preprocessed tablea. Iflastis unspecified, it defaults tos.high(the last element).Searching is case-sensitive. If
subis not ins, -1 is returned.See also:
initSkipTable func<#initSkipTable,string>_initSkipTable func<#initSkipTable,SkipTable,string>_
func find(s: string; sub: string; start: int64; last: int64): int64Searches for
subinsinside rangestart..last(both ends included). Iflastis unspecified or negative, it defaults tos.high(the last element).Searching is case-sensitive. If
subis not ins, -1 is returned. Otherwise the index returned is relative tos[0], notstart. Subtractstartfrom the result for astart-origin index.See also:
replace func<#replace,string,string,string>_
func replace(s: string; sub: char; by: char): stringReturns a copy of
swhere everysubis replaced byby.func replace(s: string; sub: string; by: string): stringReplaces every occurrence of the string
subinswith the stringby.See also:
find func<#find,string,string,Natural,int>_replace func<#replace,string,char,char>_ for replacing
single characters
replaceWord func<#replaceWord,string,string,string>_multiReplace func<#multiReplace,string,varargs[]>_ for substringsmultiReplace func<#multiReplace,openArray[char],varargs[]>_ for single characters
func replaceWord(s: string; sub: string; by: string): stringReplaces every occurrence of the string
subinswith the stringby.Each occurrence of
subhas to be surrounded by word boundaries (comparable to\bin regular expressions), otherwise it is not replaced.func multiReplace(s: string; replacements: openArray): stringSame as
replace<#replace,string,string,string>_, but specialized for doing multiple replacements in a single pass through the input string.multiReplacescans the input string from left to right and replaces the matching substrings in the same order as passed in the argument list.The implications of the order of scanning the string and matching the replacements: - In case of multiple matches at a given position, the earliest replacement is applied. - Overlaps are not handled. After performing a replacement, the scan continues from the character after the matched substring. If the resulting string then contains a possible match starting in a newly placed substring, the additional replacement is not performed.
If the resulting string is not longer than the original input string, only a single memory allocation is required.
func multiReplace(s: openArray; replacements: openArray): stringPerforms multiple character replacements in a single pass through the input.
multiReplacescans the inputsfrom left to right and replaces characters based on character sets, applying the first matching replacement at each position. Useful for sanitizing or transforming strings with predefined character mappings.The order of the
replacementsmatters: - First matching replacement is applied - Subsequent replacements are not considered for the same characterSee also:
func toHex(x: int64; len: int64): stringConverts
xto a hexadecimal string exactlylenuppercase digits wide (no0xprefix). Negative values render in two's complement, and a value needing more thanlendigits keeps only its least-significantlennibbles.func toHex(x: T): stringFull-width hex for
x:2 * sizeof(T)uppercase digits, e.g.toHex(0'u16) == "0000",toHex(255'u8) == "FF".func escape(s: string; prefix: string; suffix: string): stringEscapes a string
s... note:: The escaping scheme is different from
system.addEscapedChar.- replaces
'\0'..'\31'and'\127'..'\255'by\xHHwhereHHis its hexadecimal value - replaces
\by\\ - replaces
'by\' - replaces
"by\"
The resulting string is prefixed with
prefixand suffixed withsuffix. Both may be empty strings.See also:
addEscapedChar func<system.html#addEscapedChar,string,char>_unescape func<#unescape,string,string,string>_ for the opposite
operation
- replaces
func unescape(s: string; prefix: string; suffix: string): stringUnescapes a string
s.This complements
escape func<#escape,string,string,string>_ as it performs the opposite operations.If
sdoes not begin withprefixand end withsuffixa ValueError exception will be raised.type FloatFormatMode = enum ffDefault = (0, "ffDefault") ffDecimal = (1, "ffDecimal") ffScientific = (2, "ffScientific")
func dollar`.FloatFormatMode(e: FloatFormatMode): stringfunc formatBiggestFloat(f: float64; format: FloatFormatMode; precision: -1..32; decimalSep: char): stringConverts a floating point value
fto a string.If
format == ffDecimalthen precision is the number of digits to be printed after the decimal point. Ifformat == ffScientificthen precision is the maximum number of significant digits to be printed.precision's default value is the maximum number of meaningful digits after the decimal point for Nim'sbiggestFloattype.If
precision == -1, it tries to format it nicely.func formatFloat(f: float64; format: FloatFormatMode; precision: -1..32; decimalSep: char): stringConverts a floating point value
fto a string.If
format == ffDecimalthen precision is the number of digits to be printed after the decimal point. Ifformat == ffScientificthen precision is the maximum number of significant digits to be printed.precision's default value is the maximum number of meaningful digits after the decimal point for Nim'sfloattype.If
precision == -1, it tries to format it nicely.func %(formatstr: string; a: openArray): stringInterpolates a format string with the values from
a.The
substitution:idx: operator performs string substitutions informatstrand returns a modifiedformatstr. This is often calledstring interpolation:idx:.This is best explained by an example:
nim "$1 eats $2." % ["The cat", "fish"]Results in:
nim "The cat eats fish."The substitution variables (the thing after the
$) are enumerated from 1 toa.len. To produce a verbatim$, use$$. The notation$#can be used to refer to the next substitution variable:nim "$# eats $#." % ["The cat", "fish"]Substitution variables can also be words (that is
[A-Za-z_]+[A-Za-z0-9_]*) in which case the arguments inawith even indices are keys and with odd indices are the corresponding values. An example:nim "$animal eats $food." % ["animal", "The cat", "food", "fish"]Results in:
nim "The cat eats fish."The variables are compared with
cmpIgnoreStyle.ValueErroris raised if an ill-formed format string has been passed to the%operator.func format(formatstr: string; a: openArray): stringThis is the same as
formatstr % a(see% func<#%25,string,openArray[string]>_)func strip(s: string; leading: bool; trailing: bool; chars: set[char]): stringStrips leading or trailing
chars(default: whitespace characters) fromsand returns the resulting string.If
leadingis true (default), leadingcharsare stripped. Iftrailingis true (default), trailingcharsare stripped. If both are false, the string is returned unchanged.func trimZeros(x: var string; decimalSep: char)Trim trailing zeros from a formatted floating point value
x(must be declared asvar).This modifies
xitself, it does not return a copy.type BinaryPrefixMode = enum bpIEC = (0, "bpIEC") bpColloquial = (1, "bpColloquial")
func dollar`.BinaryPrefixMode(e: BinaryPrefixMode): stringfunc formatSize(bytes: int64; decimalSep: char; prefix: BinaryPrefixMode; includeSpace: bool): stringRounds and formats
bytes.By default, uses the IEC/ISO standard binary prefixes, so 1024 will be formatted as 1KiB. Set prefix to
bpColloquialto use the colloquial names from the SI standard (e.g. k for 1000 being reused as 1024).includeSpacecan be set to true to include the (SI preferred) space between the number and the unit (e.g. 1 KiB).See also:
strformat module<strformat.html>_ for string interpolation and formatting
func contains(s: string; sub: string): boolSame as
find(s, sub) >= 0.See also:
find func<#find,string,string,Natural,int>_
func contains(s: string; chars: set[char]): boolSame as
find(s, chars) >= 0.See also:
find func<#find,string,set[char],Natural,int>_
func parseBiggestInt(s: string): int64Parses a decimal integer value contained in
s.ValueErroris raised ifsis not a valid integer.func parseInt(s: string): int64Parses a decimal integer value contained in
s.ValueErroris raised ifsis not a valid integer.nim assert parseInt("-0042") == -42