Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a space separated list

Tags:

java

string

This is a common task I'm facing: splitting a space separated list into a head element and an array containing the tail elements. For example, given this string:

the quick brown fox

We want:

"the"
["quick","brown","fox"]

.. in two different variables. The first variable should be a string, and the second an array. I'm looking for an elegant way to do this (preferably in Java).

like image 428
Wram Avatar asked Jul 09 '10 15:07

Wram


People also ask

How do you split a list by space in Python?

Python String split() Method Python string method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.

How do you split a string into a list by spaces?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a space?

The standard solution to split a string is using the split() method provided by the String class. It accepts a regular expression as a delimiter and returns a string array. To split on any whitespace character, you can use the predefined character class \s that represents a whitespace character.


1 Answers

For certain values of elegant:

String input = "The quick brown fox";
String[] elements = input.split(" ");
String first = elements[0];
String[] trailing = Arrays.copyOfRange(elements,1,elements.length);

I can't think of a way to do it with less code...

like image 186
Alterscape Avatar answered Oct 14 '22 10:10

Alterscape