Programming |
Strings
This section covers the following topics:
Creating Strings with Concatenation
Strings are often created by concatenating smaller elements together (e.g., strings, values, etc.). Two common methods of concatenating are to use the MATLAB concatenation operator ([]
) or the sprintf
function. The second and third line below illustrate both of these methods. Both lines give the same result:
numChars = 28; s = ['There are ' int2str(numChars) ' characters here'] s = sprintf('There are %d characters here\n', numChars)
For more information: See Creating Character Arrays and Numeric/String Conversion in the MATLAB Programming documentation.
Comparing Methods of Concatenation
When building strings with concatenation, sprintf
is often preferable to []
because
You can also concatenate using the strcat
function, However, for simple concatenations, sprintf
and []
are faster.
Store Arrays of Strings in a Cell Array
It is usually best to store an array of strings in a cell array instead of a character array, especially if the strings are of different lengths. Strings in a character array must be of equal length, which often requires padding the strings with blanks. This is not necessary when using a cell array of strings that has no such requirement.
The cellRecord
below does not require padding the strings with spaces:
charRecord = ['Allison Jones'; 'Development '; 'Phoenix ']; cellRecord = {'Allison Jones'; 'Development'; 'Phoenix'};
For more information: See Cell Arrays of Strings in the MATLAB Programming documentation.
Converting Between Strings and Cell Arrays
You can convert between standard character arrays and cell arrays of strings using the cellstr
and char
functions:
Also, a number of the MATLAB string operations can be used with either character arrays, or cell arrays, or both:
cellRecord2 = {'Brian Lewis'; 'Development'; 'Albuquerque'}; strcmp(charRecord, cellRecord2) ans = 0 1 0
For more information: See Converting to a Cell Array of Strings and String Comparisons in the MATLAB Programming documentation.
Search and Replace Using Regular Expressions
Using regular expressions in MATLAB offers a very versatile way of searching for and replacing characters or phrases within a string. See the help on these functions for more information.
Function |
Description |
regexp |
Match regular expression. |
regexpi |
Match regular expression, ignoring case. |
regexprep |
Replace string using regular expression. |
For more information: See Regular Expressions in the MATLAB Programming documentation.
Variables | Evaluating Expressions |
© 1994-2005 The MathWorks, Inc.