MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
str = ["Venus","Earth","Mars"];
TF = contains(str,"Earth");

Before R2016b, the term "cell array of strings" meant a cell array whose elements all
contain character vectors. But it is more precise to refer to such cell arrays as "cell arrays
of character vectors," to distinguish them from string arrays.

Cell arrays can contain variables having any data types, including strings. It is still
possible to create a cell array whose elements all contain strings. And if you already have
specified cell arrays of character vectors in your code, then replacing single quotes with
double quotes might seem like a simple update. However, it is not recommended that you
create or use cell arrays of strings.

Why Does length() of String Return 1?


It is common to use the length function to determine the number of characters in a
character vector. But to determine the number of characters in a string, use the
strlength function, not length.

Create a character vector using single quotes. To determine its length, use the length
function. Because C is a vector, its length is equal to the number of characters. C is a 1-
by-11 vector.

C = 'Hello world';
L = length(C)

L = 11

Create a string with the same characters, using double quotes. Though it stores 11
characters, str is a 1-by-1 string array, or string scalar. If you call length on a string
scalar, then the output argument is 1 , no matter how many characters it stores.

str = "Hello World";
L = length(str)

L = 1

To determine the number of characters in a string, use the strlength function,
introduced in R2016b. For compatibility, strlength operates on character vectors as
well. In both cases strlength returns the number of characters.

L = strlength(C)

6 Characters and Strings

Free download pdf