# 12.2 Text functions

> Text functions measure, trim, search and transform strings without ever modifying the original: they always return a new one.

Web page: https://pseudolearn.app/en/spec/biblioteca/texto

> **In one sentence**
>
> Text functions measure, trim, search and transform strings without ever modifying the original: they always return a new one.

## 12.2.1 How it works

They all work by **code points**: every Unicode character counts as one, accented or not. Positions start at **zero**.

| Function | What it returns |
| --- | --- |
| `length(t)` | how many characters it has |
| `substring(t, from, to)` | the piece between two positions, both included |
| `trim(t)` | without spaces at the start or end |
| `toUpper(t)`, `toLower(t)` | with every letter changed |
| `contains`, `startsWith`, `endsWith` | a `Boolean` |
| `indexOf(t, part)` | `Something(position)` or `Nothing` |
| `replace(t, find, put)` | with every occurrence changed |
| `split(t, separator)`, `join(v, separator)` | a vector of pieces, or the joined text |
| `charAt`, `charCode`, `charFromCode` | a character or its Unicode code |
| `padLeft`, `padRight` | the text filled up to a width |

**Figure 12.2-1: Positions in a text**

The text Hola, mundo in cells numbered from 0 to 10. The first four, from 0 to 3, are highlighted as the result of substring(t, 0, 3).

Positions start at zero and `substring` includes both positions it receives: `substring(t, 0, 3)` is the first four characters.

### Program: A tour of the text functions

```pseudolearn
Algorithm Textos
  Define frase As String <- "  Hola, mundo  ";
  Define limpia As String <- trim(frase);
  Write "[", limpia, "] ", length(limpia);
  Write substring(limpia, 0, 3), " ", toUpper(limpia), " ", toLower("ÁRBOL");
  Write contains(limpia, "mundo"), " ", startsWith(limpia, "Ho"), " ", endsWith(limpia, "x");
  Write replace(limpia, "o", "0"), " ", charAt(limpia, 1), " ", charCode('A'), " ", charFromCode(97);
  Write padLeft("7", 3, '0'), " ", padRight("ab", 4, '.'), "|";
  Write join(split("a,b,c", ","), " - ");
EndAlgorithm
```

**Output**

```text
[Hola, mundo] 11
Hola HOLA, MUNDO árbol
true true false
H0la, mund0 o 65 a
007 ab..|
a - b - c
```

*The program finishes normally.*

> **Limit**
>
> - A position outside the text stops the program with `stringPositionOutOfRange`.
> - `charFromCode` only accepts valid Unicode codes: from 0 to 1114111, without the range 55296 to 57343.
> - Case changes follow full Unicode: `ß` becomes `SS`.

**In short**
- Text functions return new strings.
- They count Unicode characters and number from zero.
- `substring` includes both positions.

**See also**
- [4.6 Concatenation](https://pseudolearn.app/en/spec/expresiones/concatenacion.md)
- [12.3 Conversions](https://pseudolearn.app/en/spec/biblioteca/conversion.md)
