splitlines

Split string at newline characters

Syntax

Description

example

newStr = splitlines(str) splits str at newline characters and returns the result in newStr. If str is a string array, then each element of str must contain the same number of newlines.

splitlines splits at actual newline characters, not at the literal \n. To split a string that contains \n, first use compose and then use splitlines.

Examples

collapse all

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.

str = string('In Xanadu did Kubla Khan');
str = str + '\n' + 'A stately pleasure-dome decree'
str = 

  string

    "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 = 

  string

    "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 = 

  2×1 string array

    "In Xanadu did Kubla Khan"
    "A stately pleasure-dome decree"

Create a character vector and split it at newline characters. The newline function returns the newline character, char(10).

chr = 'Whose woods these are I think I know.';
chr = [chr newline 'His house is in the village though;']
chr =

Whose woods these are I think I know.
His house is in the village though;

splitlines returns the text as a string array even though chr is a character vector, because the string array contains more pieces of text.

str = splitlines(chr)
str = 

  2×1 string array

    "Whose woods these are I think I know."
    "His house is in the village though;"

Related Examples

Input Arguments

collapse all

Input text, specified as a string array, a character vector, or a cell array of character vectors..

Output Arguments

collapse all

Output string, returned as a string array. 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.

More About

collapse all

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.

See Also

| | | | | |

Introduced in R2016b

Was this topic helpful?