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
#include <string.h>
chunks[0] = strtok(s, " ");
for (int i = 1; i < N; ++i)
{
    chunks[i] = strtok(NULL, " ");
    
    if (!chunks[i])
        break;
}
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
var chunks = s.split(/ +/);
String[] chunks = s.split("\\s+");
chunks = {}
for substring in s:gmatch("%S+") do
   table.insert(chunks, substring)
end
1
$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();

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

Idiom created by

programming-idioms.org

Related idioms