Strings are Unicode text. Lengths and indexes count characters, not bytes; bytesize counts the UTF-8 bytes.

Aliases #

As in Ruby, s.size is the same as s.length.

length and empty? #

String.length(string: String) -> Int
String.empty?(string: String) -> Bool

length counts Unicode characters. empty? is true when there are none.

def main() -> Void
  puts("hello".length)
  puts(String.length("café"))
  puts("".empty?)
  puts("hello".empty?)
end
Output
5
4
true
false

upcase and downcase #

String.upcase(string: String) -> String
String.downcase(string: String) -> String
def main() -> Void
  puts("Hello".upcase)
  puts("Hello".downcase)
end
Output
HELLO
hello

strip #

String.strip(string: String) -> String

Removes spaces, tabs and new lines at both ends.

def main() -> Void
  puts("[" + "  hi \n".strip + "]")
end
Output
[hi]

split #

String.split(string: String, separator: String) -> List[String]

Cuts text at each separator. Every part is kept, even an empty one at either end or between two separators, so join with the same separator gives the text back. Empty text gives [""]. An empty separator gives the characters.

def main() -> Void
  puts("a,b,c".split(","))
  puts("a,,b,".split(","))
  puts("line\n".split("\n"))
  puts("".split(","))
  puts("a,,b,".split(",").join(","))
  puts("abc".split(""))
end
Output
["a", "b", "c"]
["a", "", "b", ""]
["line", ""]
[""]
a,,b,
["a", "b", "c"]

join #

List.join(list: List[String], separator: String) -> String

A method of a List[String]: puts the separator between the parts.

def main() -> Void
  puts(["a", "b", "c"].join("-"))
  puts(["x", "y"].join(", "))
end
Output
a-b-c
x, y

include?, start_with? and end_with? #

String.include?(string: String, part: String) -> Bool
String.start_with?(string: String, prefix: String) -> Bool
String.end_with?(string: String, suffix: String) -> Bool
def main() -> Void
  file = "report.txt"
  puts(file.include?("port"))
  puts(file.start_with?("rep"))
  puts(file.end_with?(".csv"))
end
Output
true
true
false

replace #

String.replace(string: String, from: String, to: String) -> String

Replaces every match.

def main() -> Void
  puts("a-b-c".replace("-", "+"))
end
Output
a+b+c

slice #

String.slice(string: String, start: Int, length: Int) -> String

Gives length characters starting at start. A range outside the text stops the program.

def main() -> Void
  puts("Agentica".slice(0, 5))
  puts("Agentica".slice(5, 3))
end
Output
Agent
ica

index_of #

String.index_of(string: String, part: String) -> Optional[Int]

Finds the first match as some(index), counted in characters (some(0) for an empty part). Missing text gives none.

def main() -> Void
  puts("banana".index_of("na"))
  puts("banana".index_of("x").none?)
end
Output
some(2)
true

at #

String.at(string: String, index: Int) -> String

Gives one character. Indexes start at 0. An index outside the string stops the program with RUNTIME-INDEX-OUT-OF-RANGE.

def main() -> Void
  puts("hello".at(1))
end
Output
e

reverse #

String.reverse(string: String) -> String
def main() -> Void
  puts("stressed".reverse)
end
Output
desserts

Repeating with * #

s * n gives n copies of s, as Ruby’s String#*. The count is an Int and comes second: 3 * "ab" and "ab" * "c" are CHECK-TYPE-MISMATCH. A negative count, or one that would make more than 256 MiB (268435456 bytes), stops the program with RUNTIME-INVALID-COUNT at the count.

def main() -> Void
  puts("ab" * 3)
  puts("=" * 10)
  puts(("x" * 0).empty?)
end
Output
ababab
==========
true

code and from_code #

String.code(string: String) -> Int
String.from_code(code: Int) -> String

code gives the Unicode number of a one-character string. from_code goes the other way, from a scalar value (0 to 0x10FFFF, no surrogates). Other input stops the program with RUNTIME-INVALID-CHARACTER.

def main() -> Void
  puts("a".code)
  puts(String.from_code("a".code + 1))
end
Output
97
b

compare #

String.compare(string: String, other: String) -> Int

Gives -1, 0 or 1, in the order sort uses: by code point, so "B" comes before "a". It is also a method: a.compare(b).

def main() -> Void
  puts("apple".compare("banana"))
  puts("b".compare("b"))
  puts("B".compare("a"))
end
Output
-1
0
-1

edit_distance and jaro_winkler #

String.edit_distance(string: String, other: String) -> Int
String.edit_distance(string: String, other: String, max: Int) -> Int
String.jaro_winkler(string: String, other: String) -> Float

Both measure how close two texts are, in characters as length counts them, and give the same result in either order. They find the nearest name in a list, as a “did you mean” hint does.

edit_distance is the Levenshtein distance: the fewest inserts, deletes and replacements of one character that turn string into other. It takes time in proportion to string.length * other.length, and memory in proportion to the shorter text. With max, the result stops at max + 1: once the distance is past max, the method gives max + 1. The work is then about length * (2 * max + 1) cells of the distance table instead of string.length * other.length, with length the longer text’s, and it ends early once the distance is past max, so a small max is fast on long texts. A negative max stops the program with RUNTIME-INVALID-COUNT. A long call of either method lets other tasks run between parts of its work, and --max-steps counts that work.

jaro_winkler is the Jaro-Winkler similarity, from 0.0 (nothing in common) to 1.0 (the same text), as Ruby’s DidYouMean::JaroWinkler computes it: when the Jaro similarity is above 0.7, each character of a common prefix of up to 4 adds a tenth of what is left to 1.0. Two empty texts give 1.0, and an empty text against another gives 0.0.

def main() -> Void
  puts("kitten".edit_distance("sitting"))
  puts("kitten".edit_distance("sitting", 2))
  puts("café".edit_distance("cafe"))
  puts("martha".jaro_winkler("marhta"))
  names = ["length", "upcase", "reverse"]
  puts(names.min_by do |name: String| name.edit_distance("lenght") end)
end
Output
3
3
1
0.9611111111111111
some("length")

to_i and to_f #

String.to_i(string: String) -> Result[Int]
String.to_f(string: String) -> Result[Float]

Read a signed decimal number. Bad text gives an error Result. A number becomes text with n.to_s.

to_f also reads an exponent (1.5E-3, 1e+20) and the text to_s writes for infinity and NaN (+inf.0, -inf.0, +nan.0), so x.to_s.to_f gives x back (a NaN reads back as NaN). It rounds to the nearest Float, and a value past the range becomes an infinity or zero. Infinity, .5 and 1_000.0 are errors.

def main() -> Void
  puts("-12".to_i)
  puts("3.5".to_f)
  puts("1e+20".to_f)
  puts("-inf.0".to_f)
  puts("abc".to_i.ok?)
end
Output
ok(-12)
ok(3.5)
ok(1e+20)
ok(-inf.0)
false

to_i! and to_f! #

String.to_i!(string: String) -> Int
String.to_f!(string: String) -> Float

Like to_i and to_f, but give the number itself and stop the program on bad text: RUNTIME-INVALID-NUMBER for text that is not a number (1e, .5, 1, 1_000.0 and Infinity for to_f!), and RUNTIME-INTEGER-OVERFLOW for an integer outside Int.

def main() -> Void
  puts("40".to_i! + 2)
  puts("1.5".to_f! * 2.0)
end
Output
42
3.0

from_bytes #

String.from_bytes(data: Bytes) -> Result[String]

Decodes UTF-8 bytes strictly: invalid, overlong, surrogate and incomplete sequences give an error Result, never replacement characters. It is the inverse of s.bytes. b.decode(encoding) reads the other encodings.

def main() -> Void
  puts(String.from_bytes("hi".bytes))
  puts(String.from_bytes(Bytes.from_list([255]).unwrap!).ok?)
end
Output
ok("hi")
false

bytes #

String.bytes(string: String) -> Bytes

Encodes the text as UTF-8, as a Bytes. It cannot fail, and String.from_bytes turns it back into the text. s.bytes.to_a gives the bytes as a list of integers from 0 to 255.

def main() -> Void
  b = "hé".bytes
  puts(b.length)
  puts(b.to_a)
end
Output
3
[104, 195, 169]

encode #

String.encode(string: String, encoding: String) -> Result[Bytes]

Writes the text as bytes in an encoding, named as for Bytes.decode: UTF-8, UTF-16, UTF-32, ASCII, Latin-1, ISO-8859-15 or Windows-1252. Plain utf-16 and utf-32 write a byte order mark and then big-endian units; the le and be forms write no mark. A character that a one-byte encoding cannot hold (€ in Latin-1, ¤ in ISO-8859-15) gives an error Result whose text ends with its index in the text, at index N, and an unknown name gives an error too. The Unicode encodings never fail. For UTF-8, use .bytes and String.from_bytes.

def main() -> Void
  puts("hé".encode("utf-16le").unwrap!.to_a)
  puts("hé".encode("utf-16").unwrap!.to_a)
  puts("hé".encode("latin-1").unwrap!.to_a)
  puts("h€".encode("latin-1"))
end
Output
[104, 0, 233, 0]
[254, 255, 0, 104, 0, 233]
[104, 233]
error("cannot encode U+20AC in Latin-1 at index 1", kind: "text.encoding")

bytesize #

String.bytesize(string: String) -> Int

Counts the UTF-8 bytes of the text, a NUL included ("é".bytesize is 2), as many as s.bytes gives, without building them. A C function that takes text with its length gets this count, with the text in a buffer of Native.from_string.

def main() -> Void
  puts("hello".bytesize)
  puts("café".bytesize)
  puts("".bytesize)
end
Output
5
5
0