Update Your Code to Accept Strings
In R2016b, MATLAB introduced string arrays as a data type for text. As of R2018b, all MathWorks
products are compatible with string arrays. Compatible means that if you can specify text as a
character vector or a cell array of character vectors, then you also can specify it as a string array.
Now you can adopt string arrays as a text data type in your own code.
If you write code for other MATLAB users, then it is to your advantage to update your API to accept
string arrays, while maintaining backward compatibility with other text data types. String adoption
makes your code consistent with MathWorks products.
If your code has few dependencies, or if you are developing new code, then consider using string
arrays as your primary text data type for better performance. In that case, best practice is to write or
update your API to accept input arguments that are character vectors, cell arrays of character
vectors, or string arrays.
For the definitions of string array and other terms, see “Terminology for Character and String Arrays”
on page 6-70.
What Are String Arrays?
In MATLAB, you can store text data in two ways. One way is to use a character array, which is a
sequence of characters, just as a numeric array is a sequence of numbers. Or, starting in R2016b, the
other way is to store a sequence of characters in a string. You can store multiple strings in a string
array. For more information, see “Characters and Strings”.
Recommended Approaches for String Adoption in Old APIs
When your code has many dependencies, and you must maintain backward compatibility, follow these
approaches for updating functions and classes to present a compatible API.
Functions
• Accept string arrays as input arguments.
• If an input argument can be either a character vector or a cell array of character vectors, then
update your code so that the argument also can be a string array. For example, consider a
function that has an input argument you can specify as a character vector (using single
quotes). Best practice is to update the function so that the argument can be specified as either
a character vector or a string scalar (using double quotes).
• Accept strings as both names and values in name-value pair arguments.
• In name-value pair arguments, allow names to be specified as either character vectors or
strings—that is, with either single or double quotes around the name. If a value can be a
character vector or cell array of character vectors, then update your code so that it also can be
a string array.
• Do not accept cell arrays of string arrays for text input arguments.
• A cell array of string arrays has a string array in each cell. For example, {"hello","world"}
is a cell array of string arrays. While you can create such a cell array, it is not recommended
for storing text. The elements of a string array have the same data type and are stored
6 Characters and Strings
6-64
Précédent

- 246/1450

Suivant