Main Content

Create String Arrays

String arrays store pieces of text and provide a set of functions for working with text as data. You can index into, reshape, and concatenate strings arrays just as you can with arrays of any other type. You also can access the characters in a string and append text to strings using the plus operator. To rearrange strings within a string array, use functions such as split, join, and sort.

Create String Arrays from Variables

MATLAB® provides string arrays to store pieces of text. Each element of a string array contains a 1-by-n sequence of characters.

You can create a string using double quotes.

str = "Hello, world"
str = 
"Hello, world"

As an alternative, you can convert a character vector to a string using the string function. chr is a 1-by-17 character vector. str is a 1-by-1 string that has the same text as the character vector.

chr = 'Greetings, friend'
chr = 
'Greetings, friend'
str = string(chr)
str = 
"Greetings, friend"

Create a string array containing multiple strings using the [] operator. str is a 2-by-3 string array that contains six strings.

str = ["Mercury","Gemini","Apollo";
       "Skylab","Skylab B","ISS"]
str = 2x3 string
    "Mercury"    "Gemini"      "Apollo"
    "Skylab"     "Skylab B"    "ISS"   

Find the length of each string in str with the strlength function. Use strlength, not length, to determine the number of characters in strings.

L = strlength(str)
L = 2×3

     7     6     6
     6     8     3

As an alternative, you can convert a cell array of character vectors to a string array using the string function. MATLAB displays strings in string arrays with double quotes, and displays characters vectors in cell arrays with single quotes.

C = {'Mercury','Venus','Earth'}
C = 1x3 cell
    {'Mercury'}    {'Venus'}    {'Earth'}

str = string(C)
str = 1x3 string
    "Mercury"    "Venus"    "Earth"

In addition to character vectors, you can convert numeric, datetime, duration, and categorical values to strings using the string function.

Convert a numeric array to a string array.

X = [5 10 20 3.1416];
ans = 1x4 string
    "5"    "10"    "20"    "3.1416"

Convert a datetime value to a string.

d = datetime('now');
ans = 
"12-Feb-2024 23:24:55"

Also, you can read text from files into string arrays using the readtable, textscan, and fscanf functions.

Create Empty and Missing Strings

String arrays can contain both empty and missing values. An empty string contains zero characters. When you display an empty string, the result is a pair of double quotes with nothing between them (""). The missing string is the string equivalent to NaN for numeric arrays. It indicates where a string array has missing values. When you display a missing string, the result is <missing>, with no quotation marks.

Create an empty string array using the strings function. When you call strings with no arguments, it returns an empty string. Note that the size of str is 1-by-1, not 0-by-0. However, str contains zero characters.

str = strings
str = 

Create an empty character vector using single quotes. Note that the size of chr is 0-by-0.

chr = ''
chr =

  0x0 empty char array

Create a string array where every element is an empty string. You can preallocate a string array with the strings function.

str = strings(2,3)
str = 2x3 string
    ""    ""    ""
    ""    ""    ""

To create a missing string, convert a missing value using the string function. The missing string displays as <missing>.

str = string(missing)
str = 

You can create a string array with both empty and missing strings. Use the ismissing function to determine which elements are strings with missing values. Note that the empty string is not a missing string.

str(1) = "";
str(2) = "Gemini";
str(3) = string(missing)
str = 1x3 string
    ""    "Gemini"    <missing>

ans = 1x3 logical array

   0   0   1

Compare a missing string to another string. The result is always 0 (false), even when you compare a missing string to another missing string.

str = string(missing);
str == "Gemini"
ans = logical

str == string(missing)
ans = logical

Access Elements of String Array

String arrays support array operations such as indexing and reshaping. Use array indexing to access the first row of str and all the columns.

str = ["Mercury","Gemini","Apollo";
       "Skylab","Skylab B","ISS"];
ans = 1x3 string
    "Mercury"    "Gemini"    "Apollo"

Access the second element in the second row of str.

ans = 
"Skylab B"

Assign a new string outside the bounds of str. MATLAB expands the array and fills unallocated elements with missing values.

str(3,4) = "Mir"
str = 3x4 string
    "Mercury"    "Gemini"      "Apollo"     <missing>
    "Skylab"     "Skylab B"    "ISS"        <missing>
    <missing>    <missing>     <missing>    "Mir"    

Access Characters Within Strings

You can index into a string array using curly braces, {}, to access characters directly. Use curly braces when you need to access and modify characters within a string element. Indexing with curly braces provides compatibility for code that could work with either string arrays or cell arrays of character vectors. But whenever possible, use string functions to work with the characters in strings.

Access the second element in the second row with curly braces. chr is a character vector, not a string.

str = ["Mercury","Gemini","Apollo";
       "Skylab","Skylab B","ISS"];
chr = str{2,2}
chr = 
'Skylab B'

Access the character vector and return the first three characters.

ans = 

Find the space characters in a string and replace them with dashes. Use the isspace function to inspect individual characters within the string. isspace returns a logical vector that contains a true value wherever there is a space character. Finally, display the modified string element, str(2,2).

TF = isspace(str{2,2})
TF = 1x8 logical array

   0   0   0   0   0   0   1   0

str{2,2}(TF) = "-";
ans = 

Note that in this case, you can also replace spaces using the replace function, without resorting to curly brace indexing.

replace(str(2,2)," ","-")
ans = 

Concatenate Strings into String Array

Concatenate strings into a string array just as you would concatenate arrays of any other kind.

Concatenate two string arrays using square brackets, [].

str1 = ["Mercury","Gemini","Apollo"];
str2 = ["Skylab","Skylab B","ISS"];
str = [str1 str2]
str = 1x6 string
    "Mercury"    "Gemini"    "Apollo"    "Skylab"    "Skylab B"    "ISS"

Transpose str1 and str2. Concatenate them and then vertically concatenate column headings onto the string array. When you concatenate character vectors into a string array, the character vectors are automatically converted to strings.

str1 = str1';
str2 = str2';
str = [str1 str2];
str = [["Mission:","Station:"] ; str]
str = 4x2 string
    "Mission:"    "Station:"
    "Mercury"     "Skylab"  
    "Gemini"      "Skylab B"
    "Apollo"      "ISS"     

Append Text to Strings

To append text to strings, use the plus operator, +. The plus operator appends text to strings but does not change the size of a string array.

Append a last name to an array of names. If you append a character vector to strings, then the character vector is automatically converted to a string.

names = ["Mary";"John";"Elizabeth";"Paul";"Ann"];
names = names + ' Smith'
names = 5x1 string
    "Mary Smith"
    "John Smith"
    "Elizabeth Smith"
    "Paul Smith"
    "Ann Smith"

Append different last names. You can append text to a string array from a string array or from a cell array of character vectors. When you add nonscalar arrays, they must be the same size.

names = ["Mary";"John";"Elizabeth";"Paul";"Ann"];
lastnames = ["Jones";"Adams";"Young";"Burns";"Spencer"];
names = names + " " + lastnames
names = 5x1 string
    "Mary Jones"
    "John Adams"
    "Elizabeth Young"
    "Paul Burns"
    "Ann Spencer"

Append a missing string. When you append a missing string with the plus operator, the output is a missing string.

str1 = "Jones";
str2 = string(missing);
str1 + str2
ans = 

Split, Join, and Sort String Array

MATLAB provides a rich set of functions to work with string arrays. For example, you can use the split, join, and sort functions to rearrange the string array names so that the names are in alphabetical order by last name.

Split names on the space characters. Splitting changes names from a 5-by-1 string array to a 5-by-2 array.

names = ["Mary Jones";"John Adams";"Elizabeth Young";"Paul Burns";"Ann Spencer"];
names = split(names)
names = 5x2 string
    "Mary"         "Jones"  
    "John"         "Adams"  
    "Elizabeth"    "Young"  
    "Paul"         "Burns"  
    "Ann"          "Spencer"

Switch the columns of names so that the last names are in the first column. Add a comma after each last name.

names = [names(:,2) names(:,1)];
names(:,1) = names(:,1) + ','
names = 5x2 string
    "Jones,"      "Mary"     
    "Adams,"      "John"     
    "Young,"      "Elizabeth"
    "Burns,"      "Paul"     
    "Spencer,"    "Ann"      

Join the last and first names. The join function places a space character between the strings it joins. After the join, names is a 5-by-1 string array.

names = join(names)
names = 5x1 string
    "Jones, Mary"
    "Adams, John"
    "Young, Elizabeth"
    "Burns, Paul"
    "Spencer, Ann"

Sort the elements of names so that they are in alphabetical order.

names = sort(names)
names = 5x1 string
    "Adams, John"
    "Burns, Paul"
    "Jones, Mary"
    "Spencer, Ann"
    "Young, Elizabeth"

See Also

| | | | | | | |

Related Topics