strsplit

Splits text at delimiters into a cell array of pieces.

Category: Language Fundamentals > Data Types

Syntax

C = strsplit(str)

Splits at whitespace.

C = strsplit(str, delimiter)

Splits at one delimiter, or at any of several given in a cell array.

C = strsplit(str, delimiter, 'CollapseDelimiters', tf)

Controls whether consecutive delimiters count as one (default true).

Description

By default, adjacent delimiters are merged into one, so 'one two three' splits into three pieces even though there are two spaces. Set 'CollapseDelimiters' to false to get an empty piece between every pair of delimiters, which preserves the field count of a CSV line with empty fields.

The inverse operation is strjoin. For string arrays, split is the counterpart.

Input arguments

str
Character vector or string.
delimiter
Delimiter text or a cell array of delimiters; escape sequences such as '\t' are interpreted.
'CollapseDelimiters'
Logical, default true.

Output arguments

C
1-by-N cell array of character vectors.

Example

Single, multiple and empty fields

strsplit('a,b,,c', ',', 'CollapseDelimiters', false)
strsplit('one two  three')
strsplit('a-b_c', {'-','_'})
Output
ans = 1×4 cell

    {'a'}    {'b'}    {0×0 char}    {'c'}
ans = 1×3 cell

    {'one'}    {'two'}    {'three'}
ans = 1×3 cell

    {'a'}    {'b'}    {'c'}

See also

strjoin split regexp textscan strtok