Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Scheme

Idiom #49 Split a space-separated string

Build list chunks consisting in substrings of the string s, separated by one or more space characters.

Turning the string "what a mess" into the 3 strings "what", "a", "mess"
(define (tokenize l)
  (let loop ((t '())
             (l l))
    (if (pair? l)
        (let ((c (car l)))
          (if (char=? c #\space)
              (cons (reverse t) (loop '() (cdr l)))
              (loop (cons (car l) t) (cdr l))))
        (if (null? t)
            '()
            (list (reverse t))))))

(define (string-split s)
  (map list->string (tokenize (string->list s))))
#include <string.h>
chunks[0] = strtok(s, " ");
for (int i = 1; i < N; ++i)
{
    chunks[i] = strtok(NULL, " ");
    
    if (!chunks[i])
        break;
}

N is the size of chunks.

strtok modifies s by adding null-characters between words.

New implementation...