Logo

Programming-Idioms

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

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"
String chunks[] = s.split(" +");
import static java.util.regex.Pattern.compile;
import java.util.Scanner;
Scanner t = new Scanner(s);
t.useDelimiter(compile(" +"));
String chunks[] = t.tokens()
    .toArray(String[]::new);
t.close();
import static java.util.regex.Pattern.compile;
import java.util.List;
import java.util.Scanner;
Scanner t = new Scanner(s);
t.useDelimiter(compile(" +"));
List<String> chunks = t.tokens().toList();
t.close();
import static java.util.Arrays.asList;
import java.util.List;
List<String> chunks = asList(s.split(" +"));

Immutable
import static java.util.List.of;
import java.util.List;
List<String> chunks = of(s.split(" +"));

Immutable
import static java.util.List.of;
import java.util.ArrayList;
import java.util.List;
List<String> chunks
    = new ArrayList<>(of(s.split(" +")));

Mutable
#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...