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).
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.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With