Tokenization

Word Count in Strings

State machines, strtok, split(), and tokenizers in C, Java, JS, and Python.

SLIDE 1 / 6

1. Tokenization Strategy

Word counting requires detecting transitions between spaces/delimiters and printable characters (Finite State Machine).

MACHINE STATES
OUT_WORD (Fuera de Palabra)En espacio / tab / \\n
IN_WORD (Dentro de Palabra)Sumar +1 en transición

2. C: Algoritmo con Máquina de Estados o strtok

En C se puede usar `strtok(str, " ")` o recorrer byte a byte con un flag `in_word`.

count_words.c
int countWords(const char *s) {
    int count = 0, in_word = 0;
    while (*s) {
        if (isspace(*s)) in_word = 0;
        else if (!in_word) { in_word = 1; count++; }
        s++;
    }
    return count;
}

3. Java: split("\\s+")

Java utiliza expresiones regulares `\\s+` para dividir por cualquier secuencia de espacios blancos.

WordCount.java
String text = "Hola  Mundo Java";
String[] words = text.trim().split("\\s+");
int total = words.length; // 3

4. JavaScript: split(/\\s+/) y filter(Boolean)

JS combina `split` con `filter(Boolean)` para eliminar tokens vacíos causados por espacios múltiples.

count.js
const text = "  Hola  JS  ";
const words = text.trim().split(/\s+/).filter(Boolean);
console.log(words.length); // 2

5. Python: len(text.split())

En Python `text.split()` sin argumentos elimina automáticamente espacios continuos en los extremos e intermedios.

count.py
text = "  Hola   Python  "
words = text.split()
count = len(words) # 2

6. Tokenization Inspector

Entrada: " Hola Mundo "
C (in_word): 2 palabras | Java: 2 tokens | JS: 2 tokens | Python: ['Hola', 'Mundo'] (len=2)