strutils

The system module defines several common functions for working with strings, such as:

  • $ for converting other data-types to strings
  • & for string concatenation
  • add for adding a new character or a string to the existing one
  • in (alias for contains) and notin for checking if a character is in a string

This module builds upon that, providing additional functionality in form of procedures, iterators and templates for strings.

import strutils

let
  numbers = @[867, 5309]
  multiLineString = "first line\nsecond line\nthird line"

let jenny = numbers.join("-")
assert jenny == "867-5309"

assert splitLines(multiLineString) ==
       @["first line", "second line", "third line"]
assert split(multiLineString) == @["first", "line", "second",
                                   "line", "third", "line"]
assert indent(multiLineString, 4) ==
       "    first line\n    second line\n    third line"
assert 'z'.repeat(5) == "zzzzz"

The chaining of functions is possible thanks to the method call syntax:

import strutils
from sequtils import map

let jenny = "867-5309"
assert jenny.split('-').map(parseInt) == @[867, 5309]

assert "Beetlejuice".indent(1).repeat(3).strip ==
       "Beetlejuice Beetlejuice Beetlejuice"

このモジュールは JavaScript ターゲットで利用できます。


関連:

  • strformat module for string interpolation and formatting
  • unicode module for Unicode UTF-8 handling
  • sequtils module for operations on container types (including strings)
  • parseutils module for lower-level parsing of tokens, numbers, identifiers, etc.
  • parseopt module for command-line parsing
  • strtabs module for efficient hash tables (dictionaries, in some programming languages) mapping from strings to strings
  • pegs module for PEG (Parsing Expression Grammar) support
  • ropes module for rope data type, which can represent very long strings efficiently
  • re module for regular expression (regex) support
  • strscans for scanf and scanp macros, which offer easier substring extraction than regular expressions

SkipTable = array[char, int]
  ソース 編集
FloatFormatMode = enum
  ffDefault,                  ## use the shorter floating point notation
  ffDecimal,                  ## use decimal floating point notation
  ffScientific                ## use scientific notation (using ``e`` character)
the different modes of floating point formatting   ソース 編集
BinaryPrefixMode = enum
  bpIEC, bpColloquial
the different names for binary prefixes   ソース 編集

定数

Whitespace = {' ', '\t', '\v', '\c', '\n', '\f'}
All the characters that count as whitespace (space, tab, vertical tab, carriage return, new line, form feed)   ソース 編集
Letters = {'A'..'Z', 'a'..'z'}
the set of letters   ソース 編集
Digits = {'0'..'9'}
the set of digits   ソース 編集
HexDigits = {'0'..'9', 'A'..'F', 'a'..'f'}
the set of hexadecimal digits   ソース 編集
IdentChars = {'a'..'z', 'A'..'Z', '0'..'9', '_'}
the set of characters an identifier can consist of   ソース 編集
IdentStartChars = {'a'..'z', 'A'..'Z', '_'}
the set of characters an identifier can start with   ソース 編集
Newlines = {'\c', '\n'}
the set of characters a newline terminator can start with (carriage return, line feed)   ソース 編集
AllChars = {'\x00'..'\xFF'}

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 proc find invalid characters in strings. 用例:

let invalid = AllChars - Digits
doAssert "01234".find(invalid) == -1
doAssert "01A34".find(invalid) == 2
  ソース 編集

プロシージャ

proc isAlphaAscii(c: char): bool {...}{.noSideEffect, procvar, gcsafe,
                               extern: "nsuIsAlphaAsciiChar", raises: [], tags: [].}

Checks whether or not character c is alphabetical.

This checks a-z, A-Z ASCII characters only. Use Unicode module for UTF-8 support.

用例:

doAssert isAlphaAscii('e') == true
doAssert isAlphaAscii('E') == true
doAssert isAlphaAscii('8') == false
  ソース 編集
proc isAlphaNumeric(c: char): bool {...}{.noSideEffect, procvar, gcsafe,
                                 extern: "nsuIsAlphaNumericChar", raises: [],
                                 tags: [].}

Checks whether or not c is alphanumeric.

This checks a-z, A-Z, 0-9 ASCII characters only.

用例:

doAssert isAlphaNumeric('n') == true
doAssert isAlphaNumeric('8') == true
doAssert isAlphaNumeric(' ') == false
  ソース 編集
proc isDigit(c: char): bool {...}{.noSideEffect, procvar, gcsafe, extern: "nsuIsDigitChar",
                          raises: [], tags: [].}

Checks whether or not c is a number.

This checks 0-9 ASCII characters only.

用例:

doAssert isDigit('n') == false
doAssert isDigit('8') == true
  ソース 編集
proc isSpaceAscii(c: char): bool {...}{.noSideEffect, procvar, gcsafe,
                               extern: "nsuIsSpaceAsciiChar", raises: [], tags: [].}
Checks whether or not c is a whitespace character.

用例:

doAssert isSpaceAscii('n') == false
doAssert isSpaceAscii(' ') == true
doAssert isSpaceAscii('\t') == true
  ソース 編集
proc isLowerAscii(c: char): bool {...}{.noSideEffect, procvar, gcsafe,
                               extern: "nsuIsLowerAsciiChar", raises: [], tags: [].}

Checks whether or not c is a lower case character.

This checks ASCII characters only. Use Unicode module for UTF-8 support.

関連:

用例:

doAssert isLowerAscii('e') == true
doAssert isLowerAscii('E') == false
doAssert isLowerAscii('7') == false
  ソース 編集
proc isUpperAscii(c: char): bool {...}{.noSideEffect, procvar, gcsafe,
                               extern: "nsuIsUpperAsciiChar", raises: [], tags: [].}

Checks whether or not c is an upper case character.

This checks ASCII characters only. Use Unicode module for UTF-8 support.

関連:

用例:

doAssert isUpperAscii('e') == false
doAssert isUpperAscii('E') == true
doAssert isUpperAscii('7') == false
  ソース 編集
proc toLowerAscii(c: char): char {...}{.noSideEffect, procvar, gcsafe,
                               extern: "nsuToLowerAsciiChar", raises: [], tags: [].}

Returns 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.

関連:

用例:

doAssert toLowerAscii('A') == 'a'
doAssert toLowerAscii('e') == 'e'
  ソース 編集
proc toLowerAscii(s: string): string {...}{.noSideEffect, procvar, gcsafe,
                                   extern: "nsuToLowerAsciiStr", raises: [],
                                   tags: [].}

Converts string s into lower case.

This works only for the letters A-Z. See unicode.toLower for a version that works for any Unicode character.

関連:

用例:

doAssert toLowerAscii("FooBar!") == "foobar!"
  ソース 編集
proc toUpperAscii(c: char): char {...}{.noSideEffect, procvar, gcsafe,
                               extern: "nsuToUpperAsciiChar", raises: [], tags: [].}

Converts character c into upper case.

This works only for the letters A-Z. See unicode.toUpper for a version that works for any Unicode character.

関連:

用例:

doAssert toUpperAscii('a') == 'A'
doAssert toUpperAscii('E') == 'E'
  ソース 編集
proc toUpperAscii(s: string): string {...}{.noSideEffect, procvar, gcsafe,
                                   extern: "nsuToUpperAsciiStr", raises: [],
                                   tags: [].}

Converts string s into upper case.

This works only for the letters A-Z. See unicode.toUpper for a version that works for any Unicode character.

関連:

用例:

doAssert toUpperAscii("FooBar!") == "FOOBAR!"
  ソース 編集
proc capitalizeAscii(s: string): string {...}{.noSideEffect, procvar, gcsafe,
                                      extern: "nsuCapitalizeAscii", raises: [],
                                      tags: [].}

Converts the first character of string s into upper case.

This works only for the letters A-Z. Use Unicode module for UTF-8 support.

関連:

用例:

doAssert capitalizeAscii("foo") == "Foo"
doAssert capitalizeAscii("-bar") == "-bar"
  ソース 編集
proc normalize(s: string): string {...}{.noSideEffect, procvar, gcsafe,
                                extern: "nsuNormalize", raises: [], tags: [].}

Normalizes the string s.

That means to convert it to lower case and remove any '_'. This should NOT be used to normalize Nim identifier names.

関連:

用例:

doAssert normalize("Foo_bar") == "foobar"
doAssert normalize("Foo Bar") == "foo bar"
  ソース 編集
proc cmpIgnoreCase(a, b: string): int {...}{.noSideEffect, gcsafe,
                                   extern: "nsuCmpIgnoreCase", procvar, raises: [],
                                   tags: [].}
英数大小文字同一視で文字列同士を比較します。返値:

0 if a == b
< 0 if a < b
> 0 if a > b

用例:

doAssert cmpIgnoreCase("FooBar", "foobar") == 0
doAssert cmpIgnoreCase("bar", "Foo") < 0
doAssert cmpIgnoreCase("Foo5", "foo4") > 0
  ソース 編集
proc cmpIgnoreStyle(a, b: string): int {...}{.noSideEffect, gcsafe,
                                    extern: "nsuCmpIgnoreStyle", procvar,
                                    raises: [], tags: [].}

Semantically the same as cmp(normalize(a), normalize(b)). つまり、一時作業用の文字列を割り当てずに最適化を行います。これは Nim の識別名との比較では使用してはいけません。Use macros.eqIdent for that.

返値:

0 if a == b
< 0 if a < b
> 0 if a > b

用例:

doAssert cmpIgnoreStyle("foo_bar", "FooBar") == 0
doAssert cmpIgnoreStyle("foo_bar_5", "FooBar4") > 0
  ソース 編集
proc split(s: string; sep: char; maxsplit: int = -1): seq[string] {...}{.noSideEffect, gcsafe,
    extern: "nsuSplitChar", raises: [], tags: [].}

The same as the split iterator (see its documentation), but is a proc that returns a sequence of substrings.

関連:

用例:

doAssert "a,b,c".split(',') == @["a", "b", "c"]
doAssert "".split(' ') == @[""]
  ソース 編集
proc split(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): seq[string] {...}{.
    noSideEffect, gcsafe, extern: "nsuSplitCharSet", raises: [], tags: [].}

The same as the split iterator (see its documentation), but is a proc that returns a sequence of substrings.

関連:

用例:

doAssert "a,b;c".split({',', ';'}) == @["a", "b", "c"]
doAssert "".split({' '}) == @[""]
  ソース 編集
proc split(s: string; sep: string; maxsplit: int = -1): seq[string] {...}{.noSideEffect, gcsafe,
    extern: "nsuSplitString", raises: [], tags: [].}

Splits the string s into substrings using a string separator.

Substrings are separated by the string sep. This is a wrapper around the split iterator.

関連:

用例:

doAssert "a,b,c".split(",") == @["a", "b", "c"]
doAssert "a man a plan a canal panama".split("a ") ==
    @["", "man ", "plan ", "canal panama"]
doAssert "".split("Elon Musk") == @[""]
doAssert "a  largely    spaced sentence".split(" ") ==
    @["a", "", "largely", "", "", "", "spaced", "sentence"]
doAssert "a  largely    spaced sentence".split(" ", maxsplit = 1) ==
    @["a", " largely    spaced sentence"]
  ソース 編集
proc rsplit(s: string; sep: char; maxsplit: int = -1): seq[string] {...}{.noSideEffect, gcsafe,
    extern: "nsuRSplitChar", raises: [], tags: [].}

The same as the rsplit iterator, but is a proc that returns a sequence of substrings.

A possible common use case for rsplit is path manipulation, particularly on systems that don't use a common delimiter.

For example, if a system had # as a delimiter, you could do the following to get the tail of the path:

var tailSplit = rsplit("Root#Object#Method#Index", '#', maxsplit=1)

Results in tailSplit containing:

@["Root#Object#Method", "Index"]

関連:

  ソース 編集
proc rsplit(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): seq[string] {...}{.
    noSideEffect, gcsafe, extern: "nsuRSplitCharSet", raises: [], tags: [].}

The same as the rsplit iterator, but is a proc that returns a sequence of substrings.

A possible common use case for rsplit is path manipulation, particularly on systems that don't use a common delimiter.

For example, if a system had # as a delimiter, you could do the following to get the tail of the path:

var tailSplit = rsplit("Root#Object#Method#Index", {'#'}, maxsplit=1)

Results in tailSplit containing:

@["Root#Object#Method", "Index"]

関連:

  ソース 編集
proc rsplit(s: string; sep: string; maxsplit: int = -1): seq[string] {...}{.noSideEffect,
    gcsafe, extern: "nsuRSplitString", raises: [], tags: [].}

The same as the rsplit iterator, but is a proc that returns a sequence of substrings.

A possible common use case for rsplit is path manipulation, particularly on systems that don't use a common delimiter.

For example, if a system had # as a delimiter, you could do the following to get the tail of the path:

var tailSplit = rsplit("Root#Object#Method#Index", "#", maxsplit=1)

Results in tailSplit containing:

@["Root#Object#Method", "Index"]

関連:

用例:

doAssert "a  largely    spaced sentence".rsplit(" ", maxsplit = 1) ==
    @["a  largely    spaced", "sentence"]
doAssert "a,b,c".rsplit(",") == @["a", "b", "c"]
doAssert "a man a plan a canal panama".rsplit("a ") ==
    @["", "man ", "plan ", "canal panama"]
doAssert "".rsplit("Elon Musk") == @[""]
doAssert "a  largely    spaced sentence".rsplit(" ") ==
    @["a", "", "largely", "", "", "", "spaced", "sentence"]
  ソース 編集
proc splitLines(s: string; keepEol = false): seq[string] {...}{.noSideEffect, gcsafe,
    extern: "nsuSplitLines", raises: [], tags: [].}

The same as the splitLines iterator (see its documentation), but is a proc that returns a sequence of substrings.

関連:

  ソース 編集
proc splitWhitespace(s: string; maxsplit: int = -1): seq[string] {...}{.noSideEffect, gcsafe,
    extern: "nsuSplitWhitespace", raises: [], tags: [].}

The same as the splitWhitespace iterator (see its documentation), but is a proc that returns a sequence of substrings.

関連:

  ソース 編集
proc toBin(x: BiggestInt; len: Positive): string {...}{.noSideEffect, gcsafe,
    extern: "nsuToBin", raises: [], tags: [].}

Converts x into its binary representation.

The resulting string is always len characters long. No leading 0b prefix is generated.

用例:

let
  a = 29
  b = 257
doAssert a.toBin(8) == "00011101"
doAssert b.toBin(8) == "00000001"
doAssert b.toBin(9) == "100000001"
  ソース 編集
proc toOct(x: BiggestInt; len: Positive): string {...}{.noSideEffect, gcsafe,
    extern: "nsuToOct", raises: [], tags: [].}

Converts x into its octal representation.

The resulting string is always len characters long. No leading 0o prefix is generated.

Do not confuse it with toOctal proc.

用例:

let
  a = 62
  b = 513
doAssert a.toOct(3) == "076"
doAssert b.toOct(3) == "001"
doAssert b.toOct(5) == "01001"
  ソース 編集
proc toHex(x: BiggestInt; len: Positive): string {...}{.noSideEffect, gcsafe,
    extern: "nsuToHex", raises: [], tags: [].}

Converts x to its hexadecimal representation.

The resulting string will be exactly len characters long. No prefix like 0x is generated. x is treated as an unsigned value.

用例:

let
  a = 62
  b = 4097
doAssert a.toHex(3) == "03E"
doAssert b.toHex(3) == "001"
doAssert b.toHex(4) == "1001"
  ソース 編集
proc toHex[T: SomeInteger](x: T): string
Shortcut for toHex(x, T.sizeof * 2)

用例:

doAssert toHex(1984'i64) == "00000000000007C0"
  ソース 編集
proc toHex(s: string): string {...}{.noSideEffect, gcsafe, raises: [], tags: [].}

Converts a bytes string to its hexadecimal representation.

The output is twice the input long. No prefix like 0x is generated.

関連:

用例:

let
  a = "1"
  b = "A"
  c = "\x00�"
doAssert a.toHex() == "31"
doAssert b.toHex() == "41"
doAssert c.toHex() == "00FF"
  ソース 編集
proc toOctal(c: char): string {...}{.noSideEffect, gcsafe, extern: "nsuToOctal", raises: [],
                            tags: [].}

Converts a character c to its octal representation.

The resulting string may not have a leading zero. Its length is always exactly 3.

Do not confuse it with toOct proc.

用例:

doAssert toOctal('1') == "061"
doAssert toOctal('A') == "101"
doAssert toOctal('a') == "141"
doAssert toOctal('!') == "041"
  ソース 編集
proc fromBin[T: SomeInteger](s: string): T

Parses a binary integer value from a string s.

If s is not a valid binary integer, ValueError is raised. s can have one of the following optional prefixes: 0b, 0B. Underscores within s are ignored.

Does not check for overflow. If the value represented by s is too big to fit into a return type, only the value of the rightmost binary digits of s is returned without producing an error.

用例:

let s = "0b_0100_1000_1000_1000_1110_1110_1001_1001"
doAssert fromBin[int](s) == 1216933529
doAssert fromBin[int8](s) == 0b10011001'i8
doAssert fromBin[int8](s) == -103'i8
doAssert fromBin[uint8](s) == 153
doAssert fromBin[int16](s) == 0b1110111010011001'i16
doAssert fromBin[uint64](s) == 1216933529'u64
  ソース 編集
proc fromOct[T: SomeInteger](s: string): T

Parses an octal integer value from a string s.

If s is not a valid octal integer, ValueError is raised. s can have one of the following optional prefixes: 0o, 0O. Underscores within s are ignored.

Does not check for overflow. If the value represented by s is too big to fit into a return type, only the value of the rightmost octal digits of s is returned without producing an error.

用例:

let s = "0o_123_456_777"
doAssert fromOct[int](s) == 21913087
doAssert fromOct[int8](s) == 0o377'i8
doAssert fromOct[int8](s) == -1'i8
doAssert fromOct[uint8](s) == 255'u8
doAssert fromOct[int16](s) == 24063'i16
doAssert fromOct[uint64](s) == 21913087'u64
  ソース 編集
proc fromHex[T: SomeInteger](s: string): T

Parses a hex integer value from a string s.

If s is not a valid hex integer, ValueError is raised. s can have one of the following optional prefixes: 0x, 0X, #. Underscores within s are ignored.

Does not check for overflow. If the value represented by s is too big to fit into a return type, only the value of the rightmost hex digits of s is returned without producing an error.

用例:

let s = "0x_1235_8df6"
doAssert fromHex[int](s) == 305499638
doAssert fromHex[int8](s) == 0xF6'i8
doAssert fromHex[int8](s) == -10'i8
doAssert fromHex[uint8](s) == 246'u8
doAssert fromHex[int16](s) == -29194'i16
doAssert fromHex[uint64](s) == 305499638'u64
  ソース 編集
proc intToStr(x: int; minchars: Positive = 1): string {...}{.noSideEffect, gcsafe,
    extern: "nsuIntToStr", raises: [], tags: [].}

Converts x to its decimal representation.

The resulting string will be minimally minchars characters long. This is achieved by adding leading zeros.

用例:

doAssert intToStr(1984) == "1984"
doAssert intToStr(1984, 6) == "001984"
  ソース 編集
proc parseInt(s: string): int {...}{.noSideEffect, procvar, gcsafe, extern: "nsuParseInt",
                            raises: [ValueError], tags: [].}

Parses a decimal integer value contained in s.

If s is not a valid integer, ValueError is raised.

用例:

doAssert parseInt("-0042") == -42
  ソース 編集
proc parseBiggestInt(s: string): BiggestInt {...}{.noSideEffect, procvar, gcsafe,
    extern: "nsuParseBiggestInt", raises: [ValueError], tags: [].}

Parses a decimal integer value contained in s.

If s is not a valid integer, ValueError is raised.

  ソース 編集
proc parseUInt(s: string): uint {...}{.noSideEffect, procvar, gcsafe,
                              extern: "nsuParseUInt", raises: [ValueError], tags: [].}

Parses a decimal unsigned integer value contained in s.

If s is not a valid integer, ValueError is raised.

  ソース 編集
proc parseBiggestUInt(s: string): BiggestUInt {...}{.noSideEffect, procvar, gcsafe,
    extern: "nsuParseBiggestUInt", raises: [ValueError], tags: [].}

Parses a decimal unsigned integer value contained in s.

If s is not a valid integer, ValueError is raised.

  ソース 編集
proc parseFloat(s: string): float {...}{.noSideEffect, procvar, gcsafe,
                                extern: "nsuParseFloat", raises: [ValueError],
                                tags: [].}

Parses a decimal floating point value contained in s.

If s is not a valid floating point number, ValueError is raised. NAN, INF, -INF are also supported (case insensitive comparison).

用例:

doAssert parseFloat("3.14") == 3.14
doAssert parseFloat("inf") == 1.0 / 0
  ソース 編集
proc parseBinInt(s: string): int {...}{.noSideEffect, procvar, gcsafe,
                               extern: "nsuParseBinInt", raises: [ValueError],
                               tags: [].}

Parses a binary integer value contained in s.

If s is not a valid binary integer, ValueError is raised. s can have one of the following optional prefixes: 0b, 0B. Underscores within s are ignored.

用例:

let
  a = "0b11_0101"
  b = "111"
doAssert a.parseBinInt() == 53
doAssert b.parseBinInt() == 7
  ソース 編集
proc parseOctInt(s: string): int {...}{.noSideEffect, gcsafe, extern: "nsuParseOctInt",
                               raises: [ValueError], tags: [].}

Parses an octal integer value contained in s.

If s is not a valid oct integer, ValueError is raised. s can have one of the following optional prefixes: 0o, 0O. Underscores within s are ignored.

  ソース 編集
proc parseHexInt(s: string): int {...}{.noSideEffect, procvar, gcsafe,
                               extern: "nsuParseHexInt", raises: [ValueError],
                               tags: [].}

Parses a hexadecimal integer value contained in s.

If s is not a valid hex integer, ValueError is raised. s can have one of the following optional prefixes: 0x, 0X, #. Underscores within s are ignored.

  ソース 編集
proc parseHexStr(s: string): string {...}{.noSideEffect, procvar, gcsafe,
                                  extern: "nsuParseHexStr", raises: [ValueError],
                                  tags: [].}

Convert hex-encoded string to byte string, e.g.:

Raises ValueError for an invalid hex values. The comparison is case-insensitive.

関連:

用例:

let
  a = "41"
  b = "3161"
  c = "00ff"
doAssert parseHexStr(a) == "A"
doAssert parseHexStr(b) == "1a"
doAssert parseHexStr(c) == "\x00�"
  ソース 編集
proc parseBool(s: string): bool {...}{.raises: [ValueError], tags: [].}

Parses a value into a bool.

If s is one of the following values: y, yes, true, 1, on, then returns true. If s is one of the following values: n, no, false, 0, off, then returns false. If s is something else a ValueError exception is raised.

用例:

let a = "n"
doAssert parseBool(a) == false
  ソース 編集
proc parseEnum[T: enum](s: string): T

Parses an enum T.

Raises ValueError for an invalid value in s. The comparison is done in a style insensitive way.

用例:

type
  MyEnum = enum
    first = "1st", second, third = "3rd"
doAssert parseEnum[MyEnum]("1_st") == first
doAssert parseEnum[MyEnum]("second") == second
doAssertRaises(ValueError):
  echo parseEnum[MyEnum]("third")
  ソース 編集
proc parseEnum[T: enum](s: string; default: T): T

Parses an enum T.

Uses default for an invalid value in s. The comparison is done in a style insensitive way.

用例:

type
  MyEnum = enum
    first = "1st", second, third = "3rd"
doAssert parseEnum[MyEnum]("1_st") == first
doAssert parseEnum[MyEnum]("second") == second
doAssert parseEnum[MyEnum]("last", third) == third
  ソース 編集
proc repeat(c: char; count: Natural): string {...}{.noSideEffect, gcsafe,
    extern: "nsuRepeatChar", raises: [], tags: [].}
Returns a string of length count consisting only of the character c.

用例:

let a = 'z'
doAssert a.repeat(5) == "zzzzz"
  ソース 編集
proc repeat(s: string; n: Natural): string {...}{.noSideEffect, gcsafe,
                                       extern: "nsuRepeatStr", raises: [], tags: [].}
Returns string s concatenated n times.

用例:

doAssert "+ foo +".repeat(3) == "+ foo ++ foo ++ foo +"
  ソース 編集
proc spaces(n: Natural): string {...}{.inline, raises: [], tags: [].}

Returns a string with n space characters. You can use this proc to left align strings.

関連:

用例:

let
  width = 15
  text1 = "Hello user!"
  text2 = "This is a very long string"
doAssert text1 & spaces(max(0, width - text1.len)) & "|" == "Hello user!    |"
doAssert text2 & spaces(max(0, width - text2.len)) & "|" ==
    "This is a very long string|"
  ソース 編集
proc align(s: string; count: Natural; padding = ' '): string {...}{.noSideEffect, gcsafe,
    extern: "nsuAlignString", raises: [], tags: [].}

Aligns a string s with padding, so that it is of length count.

padding characters (by default spaces) are added before s resulting in right alignment. If s.len >= count, no spaces are added and s is returned unchanged. If you need to left align a string use the alignLeft proc.

関連:

用例:

assert align("abc", 4) == " abc"
assert align("a", 0) == "a"
assert align("1232", 6) == "  1232"
assert align("1232", 6, '#') == "##1232"
  ソース 編集
proc alignLeft(s: string; count: Natural; padding = ' '): string {...}{.noSideEffect,
    raises: [], tags: [].}

Left-Aligns a string s with padding, so that it is of length count.

padding characters (by default spaces) are added after s resulting in left alignment. If s.len >= count, no spaces are added and s is returned unchanged. If you need to right align a string use the align proc.

関連:

用例:

assert alignLeft("abc", 4) == "abc "
assert alignLeft("a", 0) == "a"
assert alignLeft("1232", 6) == "1232  "
assert alignLeft("1232", 6, '#') == "1232##"
  ソース 編集
proc center(s: string; width: int; fillChar: char = ' '): string {...}{.noSideEffect, gcsafe,
    extern: "nsuCenterString", raises: [], tags: [].}

Return the contents of s centered in a string width long using fillChar (default: space) as padding.

The original string is returned if width is less than or equal to s.len.

関連:

用例:

let a = "foo"
doAssert a.center(2) == "foo"
doAssert a.center(5) == " foo "
doAssert a.center(6) == " foo  "
  ソース 編集
proc indent(s: string; count: Natural; padding: string = " "): string {...}{.noSideEffect,
    gcsafe, extern: "nsuIndent", raises: [], tags: [].}

Indents each line in s by count amount of padding.

Note: This does not preserve the new line characters used in s.

関連:

用例:

doAssert indent("First line\c\n and second line.", 2) ==
    "  First line\n   and second line."
  ソース 編集
proc unindent(s: string; count: Natural; padding: string = " "): string {...}{.noSideEffect,
    gcsafe, extern: "nsuUnindent", raises: [], tags: [].}

Unindents each line in s by count amount of padding. Sometimes called dedent

Note: This does not preserve the new line characters used in s.

関連:

用例:

doAssert unindent("  First line\n   and second line", 3) ==
    "First line\nand second line"
  ソース 編集
proc unindent(s: string): string {...}{.noSideEffect, gcsafe, extern: "nsuUnindentAll",
                               raises: [], tags: [].}

Removes all indentation composed of whitespace from each line in s.

関連:

用例:

let x = """      Hello
      There
    """.unindent()
doAssert x == "Hello\nThere\n"
  ソース 編集
proc delete(s: var string; first, last: int) {...}{.noSideEffect, gcsafe, extern: "nsuDelete",
                                        raises: [], tags: [].}

Deletes in s (must be declared as var) the characters at positions first ..last (both ends included).

This modifies s itself, it does not return a copy.

用例:

var a = "abracadabra"
a.delete(4, 5)
doAssert a == "abradabra"
a.delete(1, 6)
doAssert a == "ara"
a.delete(2, 999)
doAssert a == "ar"
  ソース 編集
proc startsWith(s: string; prefix: char): bool {...}{.noSideEffect, inline, raises: [],
    tags: [].}

Returns true if s starts with character prefix.

関連:

用例:

let a = "abracadabra"
doAssert a.startsWith('a') == true
doAssert a.startsWith('b') == false
  ソース 編集
proc startsWith(s, prefix: string): bool {...}{.noSideEffect, gcsafe,
                                      extern: "nsuStartsWith", raises: [], tags: [].}

Returns true if s starts with string prefix.

prefix == "" ならば true が返されます。

関連:

用例:

let a = "abracadabra"
doAssert a.startsWith("abra") == true
doAssert a.startsWith("bra") == false
  ソース 編集
proc endsWith(s: string; suffix: char): bool {...}{.noSideEffect, inline, raises: [], tags: [].}

Returns true if s ends with suffix.

関連:

用例:

let a = "abracadabra"
doAssert a.endsWith('a') == true
doAssert a.endsWith('b') == false
  ソース 編集
proc endsWith(s, suffix: string): bool {...}{.noSideEffect, gcsafe, extern: "nsuEndsWith",
                                    raises: [], tags: [].}

Returns true if s ends with suffix.

suffix == "" ならば true が返されます。

関連:

用例:

let a = "abracadabra"
doAssert a.endsWith("abra") == true
doAssert a.endsWith("dab") == false
  ソース 編集
proc continuesWith(s, substr: string; start: Natural): bool {...}{.noSideEffect, gcsafe,
    extern: "nsuContinuesWith", raises: [], tags: [].}

Returns true if s continues with substr at position start.

If substr == "" true is returned.

関連:

用例:

let a = "abracadabra"
doAssert a.continuesWith("ca", 4) == true
doAssert a.continuesWith("ca", 5) == false
doAssert a.continuesWith("dab", 6) == true
  ソース 編集
proc removePrefix(s: var string; chars: set[char] = Newlines) {...}{.gcsafe,
    extern: "nsuRemovePrefixCharSet", raises: [], tags: [].}

Removes all characters from chars from the start of the string s (in-place).

関連:

用例:

var userInput = "\c\n*~Hello World!"
userInput.removePrefix
doAssert userInput == "*~Hello World!"
userInput.removePrefix({'~', '*'})
doAssert userInput == "Hello World!"
var otherInput = "?!?Hello!?!"
otherInput.removePrefix({'!', '?'})
doAssert otherInput == "Hello!?!"
  ソース 編集
proc removePrefix(s: var string; c: char) {...}{.gcsafe, extern: "nsuRemovePrefixChar",
                                      raises: [], tags: [].}

Removes all occurrences of a single character (in-place) from the start of a string.

関連:

用例:

var ident = "pControl"
ident.removePrefix('p')
doAssert ident == "Control"
  ソース 編集
proc removePrefix(s: var string; prefix: string) {...}{.gcsafe,
    extern: "nsuRemovePrefixString", raises: [], tags: [].}

Remove the first matching prefix (in-place) from a string.

関連:

用例:

var answers = "yesyes"
answers.removePrefix("yes")
doAssert answers == "yes"
  ソース 編集
proc removeSuffix(s: var string; chars: set[char] = Newlines) {...}{.gcsafe,
    extern: "nsuRemoveSuffixCharSet", raises: [], tags: [].}

Removes all characters from chars from the end of the string s (in-place).

関連:

用例:

var userInput = "Hello World!*~\c\n"
userInput.removeSuffix
doAssert userInput == "Hello World!*~"
userInput.removeSuffix({'~', '*'})
doAssert userInput == "Hello World!"
var otherInput = "Hello!?!"
otherInput.removeSuffix({'!', '?'})
doAssert otherInput == "Hello"
  ソース 編集
proc removeSuffix(s: var string; c: char) {...}{.gcsafe, extern: "nsuRemoveSuffixChar",
                                      raises: [], tags: [].}

Removes all occurrences of a single character (in-place) from the end of a string.

関連:

用例:

var table = "users"
table.removeSuffix('s')
doAssert table == "user"
var dots = "Trailing dots......."
dots.removeSuffix('.')
doAssert dots == "Trailing dots"
  ソース 編集
proc removeSuffix(s: var string; suffix: string) {...}{.gcsafe,
    extern: "nsuRemoveSuffixString", raises: [], tags: [].}

Remove the first matching suffix (in-place) from a string.

関連:

用例:

var answers = "yeses"
answers.removeSuffix("es")
doAssert answers == "yes"
  ソース 編集
proc addSep(dest: var string; sep = ", "; startLen: Natural = 0) {...}{.noSideEffect, inline,
    raises: [], tags: [].}

Adds a separator to dest only if its length is bigger than startLen.

A shorthand for:

if dest.len > startLen: add(dest, sep)

This is often useful for generating some code where the items need to be separated by sep. sep is only added if dest is longer than startLen. The following example creates a string describing an array of integers.

用例:

var arr = "["
for x in items([2, 3, 5, 7, 11]):
  addSep(arr, startLen = len("["))
  add(arr, $x)
add(arr, "]")
doAssert arr == "[2, 3, 5, 7, 11]"
  ソース 編集
proc allCharsInSet(s: string; theSet: set[char]): bool {...}{.raises: [], tags: [].}
Returns true if every character of s is in the set theSet.

用例:

doAssert allCharsInSet("aeea", {'a', 'e'}) == true
doAssert allCharsInSet("", {'a', 'e'}) == true
  ソース 編集
proc abbrev(s: string; possibilities: openArray[string]): int {...}{.raises: [], tags: [].}

Returns the index of the first item in possibilities which starts with s, if not ambiguous.

Returns -1 if no item has been found and -2 if multiple items match.

用例:

doAssert abbrev("fac", ["college", "faculty", "industry"]) == 1
doAssert abbrev("foo", ["college", "faculty", "industry"]) == -1
doAssert abbrev("fac", ["college", "faculty", "faculties"]) == -2
doAssert abbrev("college", ["college", "colleges", "industry"]) == 0
  ソース 編集
proc join(a: openArray[string]; sep: string = ""): string {...}{.noSideEffect, gcsafe,
    extern: "nsuJoinSep", raises: [], tags: [].}
Concatenates all strings in the container a, separating them with sep.

用例:

doAssert join(["A", "B", "Conclusion"], " -> ") == "A -> B -> Conclusion"
  ソース 編集
proc join[T: not string](a: openArray[T]; sep: string = ""): string {...}{.noSideEffect, gcsafe.}
Converts all elements in the container a to strings using $, and concatenates them with sep.

用例:

doAssert join([1, 2, 3], " -> ") == "1 -> 2 -> 3"
  ソース 編集
proc initSkipTable(a: var SkipTable; sub: string) {...}{.noSideEffect, gcsafe,
    extern: "nsuInitSkipTable", raises: [], tags: [].}
Preprocess table a for sub.   ソース 編集
proc find(a: SkipTable; s, sub: string; start: Natural = 0; last = 0): int {...}{.noSideEffect,
    gcsafe, extern: "nsuFindStrA", raises: [], tags: [].}

Searches for sub in s inside range start..`last` using preprocessed table a. If last is unspecified, it defaults to s.high (the last element).

Searching is case-sensitive. If sub is not in s, -1 is returned.

  ソース 編集
proc find(s: string; sub: char; start: Natural = 0; last = 0): int {...}{.noSideEffect, gcsafe,
    extern: "nsuFindChar", raises: [], tags: [].}

Searches for sub in s inside range start..last (both ends included). If last is unspecified, it defaults to s.high (the last element).

Searching is case-sensitive. If sub is not in s, -1 is returned. Otherwise the index returned is relative to s[0], not start. Use s[start..last].rfind for a start-origin index.

関連:

  ソース 編集
proc find(s: string; chars: set[char]; start: Natural = 0; last = 0): int {...}{.noSideEffect,
    gcsafe, extern: "nsuFindCharSet", raises: [], tags: [].}

Searches for chars in s inside range start..last (both ends included). If last is unspecified, it defaults to s.high (the last element).

If s contains none of the characters in chars, -1 is returned. Otherwise the index returned is relative to s[0], not start. Use s[start..last].find for a start-origin index.

関連:

  ソース 編集
proc find(s, sub: string; start: Natural = 0; last = 0): int {...}{.noSideEffect, gcsafe,
    extern: "nsuFindStr", raises: [], tags: [].}

Searches for sub in s inside range start..last (both ends included). If last is unspecified, it defaults to s.high (the last element).

Searching is case-sensitive. If sub is not in s, -1 is returned. Otherwise the index returned is relative to s[0], not start. Use s[start..last].find for a start-origin index.

関連:

  ソース 編集
proc rfind(s: string; sub: char; start: Natural = 0; last = -1): int {...}{.noSideEffect, gcsafe,
    extern: "nsuRFindChar", raises: [], tags: [].}

Searches for sub in s inside range start..last (both ends included) in reverse -- starting at high indexes and moving lower to the first character or start. If last is unspecified, it defaults to s.high (the last element).

Searching is case-sensitive. If sub is not in s, -1 is returned. Otherwise the index returned is relative to s[0], not start. Use s[start..last].find for a start-origin index.

関連:

  ソース 編集
proc rfind(s: string; chars: set[char]; start: Natural = 0; last = -1): int {...}{.noSideEffect,
    gcsafe, extern: "nsuRFindCharSet", raises: [], tags: [].}

Searches for chars in s inside range start..last (both ends included) in reverse -- starting at high indexes and moving lower to the first character or start. If last is unspecified, it defaults to s.high (the last element).

If s contains none of the characters in chars, -1 is returned. Otherwise the index returned is relative to s[0], not start. Use s[start..last].rfind for a start-origin index.

関連:

  ソース 編集
proc rfind(s, sub: string; start: Natural = 0; last = -1): int {...}{.noSideEffect, gcsafe,
    extern: "nsuRFindStr", raises: [], tags: [].}

Searches for sub in s inside range start..last (both ends included) included) in reverse -- starting at high indexes and moving lower to the first character or start. If last is unspecified, it defaults to s.high (the last element).

Searching is case-sensitive. If sub is not in s, -1 is returned. Otherwise the index returned is relative to s[0], not start. Use s[start..last].rfind for a start-origin index.

関連:

  ソース 編集
proc count(s: string; sub: char): int {...}{.noSideEffect, gcsafe, extern: "nsuCountChar",
                                  raises: [], tags: [].}

Count the occurrences of the character sub in the string s.

関連:

  ソース 編集
proc count(s: string; subs: set[char]): int {...}{.noSideEffect, gcsafe,
                                        extern: "nsuCountCharSet", raises: [],
                                        tags: [].}

Count the occurrences of the group of character subs in the string s.

関連:

  ソース 編集
proc count(s: string; sub: string; overlapping: bool = false): int {...}{.noSideEffect, gcsafe,
    extern: "nsuCountString", raises: [], tags: [].}

Count the occurrences of a substring sub in the string s. Overlapping occurrences of sub only count when overlapping is set to true (default: false).

関連:

  ソース 編集
proc countLines(s: string): int {...}{.noSideEffect, gcsafe, extern: "nsuCountLines",
                              raises: [], tags: [].}

Returns the number of lines in the string s.

This is the same as len(splitLines(s)), but much more efficient because it doesn't modify the string creating temporal objects. Every character literal newline combination (CR, LF, CR-LF) is supported.

In this context, a line is any string separated by a newline combination. A line can be an empty string.

関連:

用例:

doAssert countLines("First line\n and second line.") == 2
  ソース 編集
proc contains(s, sub: string): bool {...}{.noSideEffect, raises: [], tags: [].}

Same as find(s, sub) >= 0.

関連:

  ソース 編集
proc contains(s: string; chars: set[char]): bool {...}{.noSideEffect, raises: [], tags: [].}

Same as find(s, chars) >= 0.

関連:

  ソース 編集
proc replace(s, sub: string; by = ""): string {...}{.noSideEffect, gcsafe,
                                        extern: "nsuReplaceStr", raises: [],
                                        tags: [].}

Replaces sub in s by the string by.

関連:

  ソース 編集
proc replace(s: string; sub, by: char): string {...}{.noSideEffect, gcsafe,
    extern: "nsuReplaceChar", raises: [], tags: [].}

Replaces sub in s by the character by.

Optimized version of replace for characters.

関連:

  ソース 編集
proc replaceWord(s, sub: string; by = ""): string {...}{.noSideEffect, gcsafe,
    extern: "nsuReplaceWord", raises: [], tags: [].}

Replaces sub in s by the string by.

Each occurrence of sub has to be surrounded by word boundaries (comparable to \b in regular expressions), otherwise it is not replaced.

  ソース 編集
proc multiReplace(s: string; replacements: varargs[(string, string)]): string {...}{.
    noSideEffect, raises: [], tags: [].}

Same as replace, but specialized for doing multiple replacements in a single pass through the input string.

multiReplace performs all replacements in a single pass, this means it can be used to swap the occurrences of "a" and "b", for instance.

If the resulting string is not longer than the original input string, only a single memory allocation is required.

The order of the replacements does matter. Earlier replacements are preferred over later replacements in the argument list.

  ソース 編集
proc insertSep(s: string; sep = '_'; digits = 3): string {...}{.noSideEffect, gcsafe,
    extern: "nsuInsertSep", raises: [], tags: [].}

Inserts the separator sep after digits characters (default: 3) from right to left.

Even though the algorithm works with any string s, it is only useful if s contains a number.

用例:

doAssert insertSep("1000000") == "1_000_000"
  ソース 編集
proc escape(s: string; prefix = "\""; suffix = "\""): string {...}{.noSideEffect, gcsafe,
    extern: "nsuEscape", raises: [], tags: [].}

Escapes a string s. See system.addEscapedChar for the escaping scheme.

The resulting string is prefixed with prefix and suffixed with suffix. Both may be empty strings.

関連:

operation

  ソース 編集
proc unescape(s: string; prefix = "\""; suffix = "\""): string {...}{.noSideEffect, gcsafe,
    extern: "nsuUnescape", raises: [ValueError], tags: [].}

Unescapes a string s.

This complements escape proc as it performs the opposite operations.

If s does not begin with prefix and end with suffix a ValueError exception will be raised.

  ソース 編集
proc validIdentifier(s: string): bool {...}{.noSideEffect, gcsafe,
                                    extern: "nsuValidIdentifier", raises: [],
                                    tags: [].}

Returns true if s is a valid identifier.

A valid identifier starts with a character of the set IdentStartChars and is followed by any number of characters of the set IdentChars.

用例:

doAssert "abc_def08".validIdentifier
  ソース 編集
proc formatBiggestFloat(f: BiggestFloat; format: FloatFormatMode = ffDefault;
                       precision: range[-1 .. 32] = 16; decimalSep = '.'): string {...}{.
    noSideEffect, gcsafe, extern: "nsu$1", raises: [], tags: [].}

Converts a floating point value f to a string.

If format == ffDecimal then precision is the number of digits to be printed after the decimal point. If format == ffScientific then 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's biggestFloat type.

If precision == -1, it tries to format it nicely.

用例:

let x = 123.456
doAssert x.formatBiggestFloat() == "123.4560000000000"
doAssert x.formatBiggestFloat(ffDecimal, 4) == "123.4560"
doAssert x.formatBiggestFloat(ffScientific, 2) == "1.23e+02"
  ソース 編集
proc formatFloat(f: float; format: FloatFormatMode = ffDefault;
                precision: range[-1 .. 32] = 16; decimalSep = '.'): string {...}{.noSideEffect,
    gcsafe, extern: "nsu$1", raises: [], tags: [].}

Converts a floating point value f to a string.

If format == ffDecimal then precision is the number of digits to be printed after the decimal point. If format == ffScientific then 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's float type.

If precision == -1, it tries to format it nicely.

用例:

let x = 123.456
doAssert x.formatFloat() == "123.4560000000000"
doAssert x.formatFloat(ffDecimal, 4) == "123.4560"
doAssert x.formatFloat(ffScientific, 2) == "1.23e+02"
  ソース 編集
proc trimZeros(x: var string; decimalSep = '.') {...}{.noSideEffect, raises: [], tags: [].}

Trim trailing zeros from a formatted floating point value x (must be declared as var).

This modifies x itself, it does not return a copy.

用例:

var x = "123.456000000"
x.trimZeros()
doAssert x == "123.456"
  ソース 編集
proc formatSize(bytes: int64; decimalSep = '.'; prefix = bpIEC; includeSpace = false): string {...}{.
    noSideEffect, raises: [], tags: [].}

Rounds and formats bytes.

By default, uses the IEC/ISO standard binary prefixes, so 1024 will be formatted as 1KiB. Set prefix to bpColloquial to use the colloquial names from the SI standard (e.g. k for 1000 being reused as 1024).

includeSpace can be set to true to include the (SI preferred) space between the number and the unit (e.g. 1 KiB).

関連:

用例:

doAssert formatSize((1'i64 shl 31) + (300'i64 shl 20)) == "2.293GiB"
doAssert formatSize((2.234 * 1024 * 1024).int) == "2.234MiB"
doAssert formatSize(4096, includeSpace = true) == "4 KiB"
doAssert formatSize(4096, prefix = bpColloquial, includeSpace = true) == "4 kB"
doAssert formatSize(4096) == "4KiB"
doAssert formatSize(5378934, prefix = bpColloquial, decimalSep = ',') == "5,13MB"
  ソース 編集
proc formatEng(f: BiggestFloat; precision: range[0 .. 32] = 10; trim: bool = true;
              siPrefix: bool = false; unit: string = ""; decimalSep = '.';
              useUnitSpace = false): string {...}{.noSideEffect, raises: [], tags: [].}

Converts a floating point value f to a string using engineering notation.

Numbers in of the range -1000.0<f<1000.0 will be formatted without an exponent. Numbers outside of this range will be formatted as a significand in the range -1000.0<f<1000.0 and an exponent that will always be an integer multiple of 3, corresponding with the SI prefix scale k, M, G, T etc for numbers with an absolute value greater than 1 and m, μ, n, p etc for numbers with an absolute value less than 1.

The default configuration (trim=true and precision=10) shows the shortest form that precisely (up to a maximum of 10 decimal places) displays the value. For example, 4.100000 will be displayed as 4.1 (which is mathematically identical) whereas 4.1000003 will be displayed as 4.1000003.

If trim is set to true, trailing zeros will be removed; if false, the number of digits specified by precision will always be shown.

precision can be used to set the number of digits to be shown after the decimal point or (if trim is true) the maximum number of digits to be shown.

formatEng(0, 2, trim=false) == "0.00"
formatEng(0, 2) == "0"
formatEng(0.053, 0) == "53e-3"
formatEng(52731234, 2) == "52.73e6"
formatEng(-52731234, 2) == "-52.73e6"

If siPrefix is set to true, the number will be displayed with the SI prefix corresponding to the exponent. For example 4100 will be displayed as "4.1 k" instead of "4.1e3". Note that u is used for micro- in place of the greek letter mu (μ) as per ISO 2955. Numbers with an absolute value outside of the range 1e-18<f<1000e18 (1a<f<1000E) will be displayed with an exponent rather than an SI prefix, regardless of whether siPrefix is true.

If useUnitSpace is true, the provided unit will be appended to the string (with a space as required by the SI standard). This behaviour is slightly different to appending the unit to the result as the location of the space is altered depending on whether there is an exponent.

formatEng(4100, siPrefix=true, unit="V") == "4.1 kV"
formatEng(4.1, siPrefix=true, unit="V") == "4.1 V"
formatEng(4.1, siPrefix=true) == "4.1" # Note lack of space
formatEng(4100, siPrefix=true) == "4.1 k"
formatEng(4.1, siPrefix=true, unit="") == "4.1 " # Space with unit=""
formatEng(4100, siPrefix=true, unit="") == "4.1 k"
formatEng(4100) == "4.1e3"
formatEng(4100, unit="V") == "4.1e3 V"
formatEng(4100, unit="", useUnitSpace=true) == "4.1e3 " # Space with useUnitSpace=true

decimalSep is used as the decimal separator.

関連:

  ソース 編集
proc addf(s: var string; formatstr: string; a: varargs[string, `$`]) {...}{.noSideEffect,
    gcsafe, extern: "nsuAddf", raises: [ValueError], tags: [].}
The same as add(s, formatstr % a), but more efficient.   ソース 編集
proc `%`(formatstr: string; a: openArray[string]): string {...}{.noSideEffect, gcsafe,
    extern: "nsuFormatOpenArray", raises: [ValueError], tags: [].}

Interpolates a format string with the values from a.

The substitution operator performs string substitutions in formatstr and returns a modified formatstr. This is often called string interpolation.

This is best explained by an example:

"$1 eats $2." % ["The cat", "fish"]

Results in:

"The cat eats fish."

The substitution variables (the thing after the $) are enumerated from 1 to a.len. To produce a verbatim $, use $$. The notation $# can be used to refer to the next substitution variable:

"$# eats $#." % ["The cat", "fish"]

Substitution variables can also be words (that is [A-Za-z_]+[A-Za-z0-9_]*) in which case the arguments in a with even indices are keys and with odd indices are the corresponding values. 用例:

"$animal eats $food." % ["animal", "The cat", "food", "fish"]

Results in:

"The cat eats fish."

The variables are compared with cmpIgnoreStyle. ValueError is raised if an ill-formed format string has been passed to the % operator.

関連:

  ソース 編集
proc `%`(formatstr, a: string): string {...}{.noSideEffect, gcsafe,
                                    extern: "nsuFormatSingleElem",
                                    raises: [ValueError], tags: [].}
This is the same as formatstr % [a] (see % proc).   ソース 編集
proc format(formatstr: string; a: varargs[string, `$`]): string {...}{.noSideEffect, gcsafe,
    extern: "nsuFormatVarargs", raises: [ValueError], tags: [].}

This is the same as formatstr % a (see % proc) except that it supports auto stringification.

関連:

  ソース 編集
proc strip(s: string; leading = true; trailing = true; chars: set[char] = Whitespace): string {...}{.
    noSideEffect, gcsafe, extern: "nsuStrip", raises: [], tags: [].}

Strips leading or trailing chars (default: whitespace characters) from s and returns the resulting string.

If leading is true (default), leading chars are stripped. If trailing is true (default), trailing chars are stripped. If both are false, the string is returned unchanged.

関連:

用例:

let a = "  vhellov   "
let b = strip(a)
doAssert b == "vhellov"
doAssert a.strip(leading = false) == "  vhellov"
doAssert a.strip(trailing = false) == "vhellov   "
doAssert b.strip(chars = {'v'}) == "hello"
doAssert b.strip(leading = false, chars = {'v'}) == "vhello"
let c = "blaXbla"
doAssert c.strip(chars = {'b', 'a'}) == "laXbl"
doAssert c.strip(chars = {'b', 'a', 'l'}) == "X"
  ソース 編集
proc stripLineEnd(s: var string) {...}{.raises: [], tags: [].}
Returns s stripped from one of these suffixes: \r, \n, \r\n, \f, \v (at most once instance). For example, can be useful in conjunction with osproc.execCmdEx. aka: chomp

用例:

var s = "foo\n\n"
s.stripLineEnd
doAssert s == "foo\n"
s = "foo\c\n"
s.stripLineEnd
doAssert s == "foo"
  ソース 編集
proc isEmptyOrWhitespace(s: string): bool {...}{.noSideEffect, procvar, gcsafe,
                                        extern: "nsuIsEmptyOrWhitespace",
                                        raises: [], tags: [].}
Checks if s is empty or consists entirely of whitespace characters.   ソース 編集
proc isNilOrWhitespace(s: string): bool {...}{.noSideEffect, procvar, gcsafe,
                                      extern: "nsuIsNilOrWhitespace", deprecated: "use isEmptyOrWhitespace instead",
                                      raises: [], tags: [].}
Deprecated: use isEmptyOrWhitespace instead
Alias for isEmptyOrWhitespace   ソース 編集

イテレータ

iterator split(s: string; sep: char; maxsplit: int = -1): string {...}{.raises: [], tags: [].}

Splits the string s into substrings using a single separator.

Substrings are separated by the character sep. The code:

for word in split(";;this;is;an;;example;;;", ';'):
  writeLine(stdout, word)

Results in:

""
""
"this"
"is"
"an"
""
"example"
""
""
""

関連:

  ソース 編集
iterator split(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): string {...}{.
    raises: [], tags: [].}

Splits the string s into substrings using a group of separators.

Substrings are separated by a substring containing only seps.

for word in split("this\lis an\texample"):
  writeLine(stdout, word)

...generates this output:

"this"
"is"
"an"
"example"

And the following code:

for word in split("this:is;an$example", {';', ':', '$'}):
  writeLine(stdout, word)

...produces the same output as the first example. The code:

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"

関連:

  ソース 編集
iterator split(s: string; sep: string; maxsplit: int = -1): string {...}{.raises: [], tags: [].}

Splits the string s into substrings using a string separator.

Substrings are separated by the string sep. The code:

for word in split("thisDATAisDATAcorrupted", "DATA"):
  writeLine(stdout, word)

Results in:

"this"
"is"
"corrupted"

関連:

  ソース 編集
iterator rsplit(s: string; sep: char; maxsplit: int = -1): string {...}{.raises: [], tags: [].}
Splits the string s into substrings from the right using a string separator. Works exactly the same as split iterator except in reverse order.
for piece in "foo:bar".rsplit(':'):
  echo piece

Results in:

"bar"
"foo"

Substrings are separated from the right by the char sep.

関連:

  ソース 編集
iterator rsplit(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): string {...}{.
    raises: [], tags: [].}
Splits the string s into substrings from the right using a string separator. Works exactly the same as split iterator except in reverse order.
for piece in "foo bar".rsplit(WhiteSpace):
  echo piece

Results in:

"bar"
"foo"

Substrings are separated from the right by the set of chars seps

関連:

  ソース 編集
iterator rsplit(s: string; sep: string; maxsplit: int = -1; keepSeparators: bool = false): string {...}{.
    raises: [], tags: [].}
Splits the string s into substrings from the right using a string separator. Works exactly the same as split iterator except in reverse order.
for piece in "foothebar".rsplit("the"):
  echo piece

Results in:

"bar"
"foo"

Substrings are separated from the right by the string sep

関連:

  ソース 編集
iterator splitLines(s: string; keepEol = false): string {...}{.raises: [], tags: [].}

Splits the string s into its containing lines.

Every character literal newline combination (CR, LF, CR-LF) is supported. The result strings contain no trailing end of line characters unless parameter keepEol is set to true.

用例:

for line in splitLines("\nthis\nis\nan\n\nexample\n"):
  writeLine(stdout, line)

Results in:

""
"this"
"is"
"an"
""
"example"
""

関連:

  ソース 編集
iterator splitWhitespace(s: string; maxsplit: int = -1): string {...}{.raises: [], tags: [].}

Splits the string s at whitespace stripping leading and trailing whitespace if necessary. If maxsplit is specified and is positive, no more than maxsplit splits is made.

The following code:

let s = "  foo \t bar  baz  "
for ms in [-1, 1, 2, 3]:
  echo "------ maxsplit = ", ms, ":"
  for item in s.splitWhitespace(maxsplit=ms):
    echo '"', item, '"'

...results in:

------ maxsplit = -1:
"foo"
"bar"
"baz"
------ maxsplit = 1:
"foo"
"bar  baz  "
------ maxsplit = 2:
"foo"
"bar"
"baz  "
------ maxsplit = 3:
"foo"
"bar"
"baz"

関連:

  ソース 編集
iterator tokenize(s: string; seps: set[char] = Whitespace): tuple[token: string,
    isSep: bool] {...}{.raises: [], tags: [].}

Tokenizes the string s into substrings.

Substrings are separated by a substring containing only seps. 用例:

for word in tokenize("  this is an  example  "):
  writeLine(stdout, word)

Results in:

("  ", true)
("this", false)
(" ", true)
("is", false)
(" ", true)
("an", false)
("  ", true)
("example", false)
("  ", true)
  ソース 編集