# String

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?

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

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

```agentica
def main() -> Void
  puts("hello".length)
  puts(String.length("café"))
  puts("".empty?)
  puts("hello".empty?)
end
```

```output
5
4
true
false
```

## upcase and downcase

```signature
String.upcase(string: String) -> String
String.downcase(string: String) -> String
```

```agentica
def main() -> Void
  puts("Hello".upcase)
  puts("Hello".downcase)
end
```

```output
HELLO
hello
```

## strip

```signature
String.strip(string: String) -> String
```

Removes spaces, tabs and new lines at both ends.

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

```output
[hi]
```

## split

```signature
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.

```agentica
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

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

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

```agentica
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?

```signature
String.include?(string: String, part: String) -> Bool
String.start_with?(string: String, prefix: String) -> Bool
String.end_with?(string: String, suffix: String) -> Bool
```

```agentica
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

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

Replaces every match.

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

```output
a+b+c
```

## slice

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

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

```agentica
def main() -> Void
  puts("Agentica".slice(0, 5))
  puts("Agentica".slice(5, 3))
end
```

```output
Agent
ica
```

## index_of

```signature
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`.

```agentica
def main() -> Void
  puts("banana".index_of("na"))
  puts("banana".index_of("x").none?)
end
```

```output
some(2)
true
```

## at

```signature
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`.

```agentica
def main() -> Void
  puts("hello".at(1))
end
```

```output
e
```

## reverse

```signature
String.reverse(string: String) -> String
```

```agentica
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.

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

```output
ababab
==========
true
```

## code and from_code

```signature
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`.

```agentica
def main() -> Void
  puts("a".code)
  puts(String.from_code("a".code + 1))
end
```

```output
97
b
```

## compare

```signature
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)`.

```agentica
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

```signature
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`.

```agentica
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

```signature
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`](https://www.agentica-lang.com/agentica/library/text-and-data/numbers/index.md#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.

```agentica
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!

```signature
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`.

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

```output
42
3.0
```

## from_bytes

```signature
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`](https://www.agentica-lang.com/agentica/library/text-and-data/string/index.md#bytes). [`b.decode(encoding)`](https://www.agentica-lang.com/agentica/library/data-structures/bytes/index.md#decode) reads the other encodings.

```agentica
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

```signature
String.bytes(string: String) -> Bytes
```

Encodes the text as UTF-8, as a [`Bytes`](https://www.agentica-lang.com/agentica/library/data-structures/bytes/index.md). 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.

```agentica
def main() -> Void
  b = "hé".bytes
  puts(b.length)
  puts(b.to_a)
end
```

```output
3
[104, 195, 169]
```

## encode

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

Writes the text as bytes in an encoding, named as for [`Bytes.decode`](https://www.agentica-lang.com/agentica/library/data-structures/bytes/index.md#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`](https://www.agentica-lang.com/agentica/library/text-and-data/string/index.md#bytes) and [`String.from_bytes`](https://www.agentica-lang.com/agentica/library/text-and-data/string/index.md#from_bytes).

```agentica
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

```signature
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`](https://www.agentica-lang.com/agentica/library/io-and-system/native/types/index.md#owned-buffers-and-typed-memory).

```agentica
def main() -> Void
  puts("hello".bytesize)
  puts("café".bytesize)
  puts("".bytesize)
end
```

```output
5
5
0
```
