www.gusucode.com > matlab 案例源码 matlab代码程序 > matlab/RepresentTextWithCharacterAndStringArraysExample.m
%% Represent Text with Character and String Arrays % There are two ways to represent text in MATLAB(R). You can store text in % character arrays. A typical use is to store short pieces of text as _character vectors_. % And starting in R2016b, you can also store multiple pieces of text in string arrays. % String arrays provide a set of functions for working with text as data. %% Represent Text with Character Vectors % Create a character vector by enclosing a sequence of characters in single % quotation marks. MATLAB(R) displays character vectors without any % quotation marks. chr = 'Hello, world' %% % Character vectors store characters as 1-by-N vectors. You can index % directly into character vectors to get characters, or to change them. chr(1:5) %% chr(1:5) = 'HELLO'; chr %% % You can work with character vectors just as you would with arrays of any % other type. For example, you can concatenate character vectors. street = '123 Maple St.'; city = 'Lakeview, MA 01234'; fullAddress = [street ', ' city] %% % Typical uses for character vectors include specifying file names, plot % labels, or input arguments for functions. For more information on % character arrays, see <docid:matlab_prog.brah_1g>. % %% Represent Text with String Arrays % Starting in R2016b, you can store text in string arrays. Each element of a % string array stores a 1-by-N character vector. You can create a string by % converting a character vector with the |string| function. MATLAB(R) always % displays strings with double quotes. str = string('Welcome, friend') %% % |str| is a 1-by-1 string, or string scalar. To find the number of % characters in a string, use the |strlength| function. whos str %% strlength(str) %% % You can store multiple pieces of text in a string array. Each element of % the array can contain a string of a different size. To convert a cell % array of character vectors to a string array, use the |string| function. C = {'Mercury','Gemini','Apollo';... 'Skylab','Skylab B','ISS'}; str = string(C) %% % |str| is a 2-by-3 string array. You can find the lengths of the strings % with the |strlength| function. whos str %% L = strlength(str) %% % Use string arrays to store and work with multiple pieces of text. You can % find and replace substrings, sort and reshape string arrays, and work % with text as data in R2016b. For more information on string arrays, see % <docid:matlab_prog.bvbc7c5>.