Objective

Create two variants of a function to split a given string at a given delimiter.

Difficulty

Easy

Description

Splitting a string into an array of substrings is an extremely common task while working with them.

The split() string method is used in this regard. It accepts a delimiter string which specifies exactly where we wish to split the main string at.

For instance, given the string 'a|b|c', if we split it with '|' as delimiter, we'd get the array ['a', 'b', 'c']. See how the delimiter itself is chopped off from the main string with the remaining substring bits held on in an array.

As another example, if given the string 'a, b, c,d', and the delimiter ', ' (with the space character included), then splitting the string at this delimiter would yield the array ['a', 'b', 'c,d'] (comprised of 3 elements).

Simple?

In this exercise, you have to define two variants of a function stringSplit() that splits a string into an array of substrings, at a given delimiter.

These variants are detailed as follows.

Variant 1

In the first variant, it must be assumed that the delimiter is not more than 1 character in length.

Shown below are a couple of examples of this function:

stringSplit('a|b|c', '|')
['a', 'b', 'c']
stringSplit('a b c', ' ')
['a', 'b', 'c']
stringSplit('a, b, c', '')
['a', ',', ' ', 'b', ',', ' ', 'c']

Note that if the given delimiter is an empty string, the function must return back an array of all the characters, as in the last statement above.

Variant 2

In the second variant, the delimiter string could be of any arbitrary length.

This is a more general implementation of a string splitting algorithm than the one above where we assumed that the delimiter is either '' or comprised of just one character.

Shown below are a couple of examples:

stringSplit('a||b||c', '||')
['a', 'b', 'c']
stringSplit('a : b : c', ' : ')
['a', 'b', 'c']
stringSplit('aZZZbZZZc', 'ZZZ')
['a', 'b', 'c']
stringSplit('aZZZbZZZc', 'ZZ')
['a', 'Zb', 'Zc']
stringSplit('a, b, c', '')
['a', ',', ' ', 'b', ',', ' ', 'c']

Note that, as with the first variant, if the given delimiter is an empty string, the function must return back an array of all the characters.