Split a string at a newline character. When the literal \n represents a newline character, convert it to an actual newline using the compose function. Then use splitlines to split the string at the newline character.
Create a string in which two lines of text are separated by \n. You can use + to concatenate text onto the end of a string. Starting in R2017a, you can create strings using double quotes.
str = "In Xanadu did Kubla Khan";
str = str + "\n" + "A stately pleasure-dome decree"
str =
"In Xanadu did Kubla Khan\nA stately pleasure-dome decree"
Convert \n into an actual newline character. Although str displays on two lines, str is a 1-by-1 string containing both lines of text.
str = compose(str)
str =
"In Xanadu did Kubla Khan
A stately pleasure-dome decree"
Split str at the newline character. newStr is a 1-by-2 string array. Each element contains one line of the text.
newStr = splitlines(str)
newStr = 2x1 string
"In Xanadu did Kubla Khan"
"A stately pleasure-dome decree"
str — Input text string array | character vector | cell array of character vectors
Input text, specified as a string array, a character vector,
or a cell array of character vectors. If str is
a string array or cell array of character vectors, then each element
of str must contain the same number of newlines.
newStr — Output text string array | cell array of character vectors
Output text, returned as a string array or a cell array of character
vectors. newStr has one more dimension than str.
The size of the new dimension is one more than the number of newlines
in a string element. splitlines assigns the results
of the split along the new dimension. For example, if str is
a 2-by-3 string array, and each
string has three newline characters, then newStr is
a 2-by-3-by-4 array.
If the input array str is a string array,
then so is newStr. Otherwise, newStr is
a cell array of character vectors.
Tips
If the elements of a string array have different numbers of
newline characters, use a for-loop to access the
string elements individually and split them.
Extended Capabilities
Tall Arrays Calculate with arrays that have more rows than fit in memory.
This function fully supports tall arrays. For
more information, see Tall Arrays.