Main Content

splitlines

Split strings at newline characters

Description

newStr = splitlines(str) splits str at newline characters and returns the result as the output array newStr.

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.

example

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

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;'

C = splitlines(chr)
C = 2x1 cell
    {'Whose woods these are I think I know.'}
    {'His house is in the village though;'  }

Input Arguments

collapse all

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.

Output Arguments

collapse all

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

Version History

Introduced in R2016b