What is the difference between string and character class in MATLAB?
a = \'AX\'; % This is a character.
b = string(a) % This is a string.
The best place to start for understanding the difference is the documentation. The key difference, as stated there:
- A character array is a sequence of characters, just as a numeric array is a sequence of numbers. A typical use is to store short pieces of text as character vectors, such as
c = 'Hello World';.- A string array is a container for pieces of text. String arrays provide a set of functions for working with text as data. To convert text to string arrays, use the
stringfunction.
Here are a few more key points about their differences:
Since a string is a container class, be mindful of how its size differs from an equivalent character array representation. Using your example:
>> a = 'AX'; % This is a character.
>> b = string(a) % This is a string.
>> whos
Name Size Bytes Class Attributes
a 1x2 4 char
b 1x1 134 string
Notice that the string container lists its size as 1x1 (and takes up more bytes in memory) while the character array is, as its name implies, a 1x2 array of characters.
They can't always be used interchangeably, and you may need to convert between the two for certain operations. For example, string objects can't be used as dynamic field names for structure indexing:
>> s = struct('a', 1);
>> name = string('a');
>> s.(name)
Argument to dynamic structure reference must evaluate to a valid field name.
>> s.(char(name))
ans =
1