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

Idiom #49 Split a space-separated string

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

Illustration
program main
use stringifor_string_t ! https://github.com/szaghi/StringiFor
   implicit none
   type( string ) ::  string1
   type( string ), allocatable :: substrings( : )
   integer :: i

   string1 =  " Build list _chunks consisting in substrings of input string _s  separated by one or more space characters"
   call string1%split(sep=' ', tokens=substrings )
   do i=1,size(substrings, dim=1)
   write(*,*) substrings(i)
   enddo
end program main
#include <string.h>
chunks[0] = strtok(s, " ");
for (int i = 1; i < N; ++i)
{
    chunks[i] = strtok(NULL, " ");
    
    if (!chunks[i])
        break;
}
(require '[clojure.string :refer [split]])
(def chunks (split s #"\s+"))
#include <sstream>
#include <algorithm>
#include <iterator>
#include <list>
std::istringstream x(s);
std::list<std::string> chunks;
std::copy(std::istream_iterator<std::string>(x), std::istream_iterator<std::string>(), std::back_inserter(chunks));
string[] chunks = s.Split(' ');
import std.range;
auto chunks = s.splitter;
s.split(new RegExp('\\s+'))
chunks = String.split(s)
Chunks = string:tokens(S, [$\s]).
import "strings"
chunks := strings.Fields(s)
import "strings"
chunks := strings.Split(s, " ")
chunks = words s
let chunks = s.split(/ +/);
String[] chunks = s.split("\\s+");
chunks = {}
for substring in s:gmatch("%S+") do
   table.insert(chunks, substring)
end
$chunks = preg_split('/ +/', $s);
Uses Classes;
chunks.StrictDelimiter := True;
chunks.Delimiter := ' ';
chunks.DelimitedText := s;
@chunks = split /\s+/, $s;
chunks = s.split()
chunks = s.split
let chunks:Vec<_> = s.split_whitespace().collect();
val chunks = s.split(" ")
(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))))

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms