• If your class already has a char and/or a cellstr method, then add a string method. If you
can represent an object of your class as a character vector or cell array of character vectors,
then represent it as a string array too.
How to Adopt String Arrays in Old APIs
You can adopt strings in old APIs by accepting string arrays as input arguments, and then converting
them to character vectors or cell arrays of character vectors. If you perform such a conversion at the
start of a function, then you do not need to update the rest of it.
The convertStringsToChars function provides a way to process all input arguments, converting
only those arguments that are string arrays. To enable your existing code to accept string arrays as
inputs, add a call to convertStringsToChars at the beginnings of your functions and methods.
For example, if you have defined a function myFunc that accepts three input arguments, process all
three inputs using convertStringsToChars. Leave the rest of your code unaltered.
function y = myFunc(a,b,c)
[a,b,c] = convertStringsToChars(a,b,c);


...
In this example, the arguments [a,b,c] overwrite the input arguments in place. If any input
argument is not a string array, then it is unaltered.
If myFunc accepts a variable number of input arguments, then process all the arguments specified by
varargin.
function y = myFunc(varargin)
[varargin{:}] = convertStringsToChars(varargin{:});
...
Performance Considerations
The convertStringsToChars function is more efficient when converting one input argument. If
your function is performance sensitive, then you can convert input arguments one at a time, while
still leaving the rest of your code unaltered.
function y = myFunc(a,b,c)
a = convertStringsToChars(a);
b = convertStringsToChars(b);
c = convertStringsToChars(c);
...
Recommended Approaches for String Adoption in New Code
When your code has few dependencies, or you are developing entirely new code, consider using
strings arrays as the primary text data type. String arrays provide good performance and efficient
memory usage when working with large amounts of text. Unlike cell arrays of character vectors,
string arrays have a homogeneous data type. String arrays make it easier to write maintainable code.
To use string arrays while maintaining backward compatibility to other text data types, follow these
approaches.
6 Characters and Strings
6-66
Précédent

- 248/1450

Suivant