split

Splits text at delimiters into separate pieces.

Category: Language Fundamentals > Data Types

Syntax

C = split(str)

Splits at whitespace.

C = split(str, delim)

Splits at the delimiter delim, or at any of several delimiters given as an array.

C = split(___, 'CollapseDelimiters', tf)

Controls whether adjacent delimiters count as one.

[C, matches] = split(___)

Also returns the delimiters found.

Description

split always returns one more piece than it finds delimiters. For an array input, the pieces run along a new dimension. By default adjacent delimiters are collapsed into one, so "a--b" split at "-" gives a and b. To split at several different characters, pass a string array such as [",", ";"].

The output is a string array when the input is a string and a cell array when the input is a char vector. strsplit is the older equivalent for char vectors.

Input arguments

str
String array, character vector or cell array of character vectors.
delim
Delimiter text, an array of delimiters, or a pattern.

Output arguments

C
For a single string input, a column string array of the pieces; for a char vector, a cell array.
matches
The delimiters that separated the pieces.

Example

split("a,b,c", ",")
split("one two three")
split("a1b2c", ["1","2"])
Output
ans = 3×1 string array

    "a"
    "b"
    "c"
ans = 3×1 string array

    "one"
    "two"
    "three"
ans = 3×1 string array

    "a"
    "b"
    "c"

Notes

In MatLivre the 'CollapseDelimiters' default is not applied (adjacent delimiters give empty pieces) and the second output matches is not available.

See also

strsplit splitlines join regexp extractBefore strtok