example
C
= strsplit(
str
)
splits the string,
str
, at whitespace into the cell array of strings,
C
. A whitespace character is equivalent to any sequence in the set
{' ','\f','\n','\r','\t','\v'}
.
example
C
= strsplit(
str
,
delimiter
)
splits
str
at the delimiters specified by
delimiter
.
example
C
= strsplit(
str
,
delimiter
,
Name,Value
)
specifies additional delimiter options using one or more name-value pair arguments.
Split a string of comma-separated values.
data = '1.21, 1.985, 1.955, 2.015, 1.885';
C = strsplit(data,', ')
'1.21' '1.985' '1.955' '2.015' '1.885'
Split a string of values,
data
, which contains the units
m/s
with an arbitrary number of white-space on either side of the text. The regular expression,
\s*
, matches any white-space character appearing zero or more times.
data = '1.21m/s1.985m/s 1.955 m/s2.015 m/s 1.885m/s';
[C,matches] = strsplit(data,'\s*m/s\s*',...
'DelimiterType','RegularExpression')
'1.21' '1.985' '1.955' '2.015' '1.885' ''
matches =
'm/s' 'm/s ' ' m/s' ' m/s ' 'm/s'
In this case, the last string in
C
is empty. This empty string is the string that follows the last matched delimiter.
Split a string on
' '
and
'ain'
, treating multiple delimiters as one. Specify multiple delimiters in a cell array of strings.
str = 'The rain in Spain stays mainly in the plain.';
[C,matches] = strsplit(str,{' ','ain'},'CollapseDelimiters',true)
'The' 'r' 'in' 'Sp' 'stays' 'm' 'ly' 'in' 'the' 'pl' '.'
matches =
' ' 'ain ' ' ' 'ain ' ' ' 'ain' ' ' ' ' ' ' 'ain'
Split the same string on whitespace and on
'ain'
, using regular expressions and treating multiple delimiters separately.
[C,matches] = strsplit(str,{'\s','ain'},'CollapseDelimiters',...
false, 'DelimiterType','RegularExpression')
'The' 'r' '' 'in' 'Sp' '' 'stays' 'm' 'ly' 'in' 'the' 'pl' '.'
matches =
' ' 'ain' ' ' ' ' 'ain' ' ' ' ' 'ain' ' ' ' ' ' ' 'ain'
In this case,
strsplit
treats the two delimiters separately, so empty strings appear in output
C
between the consecutively matched delimiters.
Split text on the strings
', '
and
', and '
.
str = 'bacon, lettuce, and tomato';
[C,matches] = strsplit(str,{', ',', and '})
'bacon' 'lettuce' 'and tomato'
matches =
', ' ', '
Because the command lists
', '
first and
', and '
contains
', '
, the
strsplit
function splits
str
on the first delimiter and never proceeds to the second delimiter.
If you reverse the order of delimiters,
', and '
takes priority.
str = 'bacon, lettuce, and tomato';
[C,matches] = strsplit(str,{', and ',', '})
'bacon' 'lettuce' 'tomato'
matches =
', ' ', and '