www.gusucode.com > matlab 案例源码 matlab代码程序 > matlab/CreateAndWorkWithStringArraysExample.m
%% Create String Arrays % String arrays are containers for pieces of text and provide a set of % functions for working with text as data. You can index into, reshape, and % concatenate strings arrays just as you can with arrays of any other type. % You can also access the characters in a string and append text to strings % using the |plus| operator. To rearrange strings within a string array, % use functions such as |split|, |join|, and |sort|. %% Create String Arrays from Variables % % Starting in R2016b, MATLAB(R) provides string arrays to store pieces of text. % Each element of a string array contains a 1-by-N character vector. % % Create a string from a character vector with the |string| function. The input % argument is a 1-by-12 character vector. |str| is a 1-by-1 string that % contains the text from the character vector. chr = 'Hello, world' %% str = string(chr) %% % Create a string array from a cell array containing many character % vectors. |str| is a 2-by-3 string array and has the same shape as |C|. % MATLAB(R) displays strings in string arrays with double % quotes, and displays characters vectors in cell arrays with single quotes. C = {'Mercury','Gemini','Apollo'; 'Skylab','Skylab B','ISS'} %% str = string(C) %% % Find the length of each string in |str| with the |strlength| function. % Use |strlength|, not |length|, to determine the number of characters in % strings. L = strlength(str) %% % In addition to character vectors, you can convert numeric, datetime, % duration, and categorical values to strings using the |string| function. % % Convert a numeric array to a string array. X = [5 10 20 3.1416]; string(X) %% % Convert a datetime value to a string. d = datetime('now'); string(d) %% % Also, you can read text from files into string arrays using the |readtable|, % |textscan|, and |fscanf| functions. %% Create Empty and Missing Strings % String arrays can contain both empty and missing values. An empty string % contains zero characters. When you display an empty string, the result is % a pair of double quotes with nothing between them (|""|). The missing % string is the string equivalent to |NaN| for numeric arrays. It indicates % where a string array has missing values. When you display a missing % string, the result is |<missing>|, with no quotation marks. % % Create an empty string array using the |strings| function. When you call % |strings| with no arguments, it returns an empty string. Note that the % size of |str| is 1-by-1, not 0-by-0. However, |str| contains zero % characters. str = strings %% % Create an empty character vector using single quotes. Note that the % size of |chr| is 0-by-0. chr = '' %% % Create a string array where every element is an empty string. You can preallocate a % string array with the |strings| function. str = strings(2,3) %% % To create a missing string, convert a |NaN| value using the |string| function. % The missing string displays as |<missing>|, with no quotation marks. str = string(nan) %% % You can create a string array with both empty and missing strings. Use the % |ismissing| function to determine which elements are strings with missing values. % Note that the empty string is not a missing string. str(1) = string(''); str(2) = string('Gemini'); str(3) = string(nan) %% ismissing(str) %% % Compare a missing string to another string. The result is always |0| (|false|), % even when you compare a missing string to another missing string. str = string(nan); str == string('Gemini') %% str == string(nan) %% Access Elements of String Array % String arrays support array operations such as indexing and reshaping. Use % array indexing to access the first row of |str| and all of the columns. str = string({'Mercury','Gemini','Apollo'; 'Skylab','Skylab B','ISS'}); str(1,:) %% % Access the second element in the second row of |str|. str(2,2) %% % Assign a new string outside the bounds of |str|. MATLAB(R) expands the % array and fills unallocated elements with missing values. When you % assign a character vector as a new string element, MATLAB(R) % automatically converts it to a string. str(3,4) = 'Mir' %% Access Characters Within Strings % You can index into a string array using curly braces, |{}|, to access characters % directly. Use curly braces when you need to access and modify characters % within a string element. Indexing with curly braces provides compatibility for % code that could work with either string arrays or cell arrays of % character vectors. But whenever possible, use string functions to work % with the characters in strings. % % Access the second element in the second row with curly braces. |chr| is a % character vector, not a string. str = string({'Mercury','Gemini','Apollo'; 'Skylab','Skylab B','ISS'}); chr = str{2,2} %% % Access the character vector and return the first three characters. str{2,2}(1:3) %% % Find the space characters in a string and replace them with dashes. Use % the |isspace| function to inspect individual characters within the % string. |isspace| returns a logical vector that contains a true value % wherever there is a space character. Finally, display the modified string % element, |str(2,2)|. tf = isspace(str{2,2}) %% str{2,2}(tf) = '-'; str(2,2) %% % Note that in this case, you can also replace spaces using the |replace| % function, without resorting to curly brace indexing. replace(str(2,2),' ','-') %% Concatenate Strings into String Array % Concatenate strings into a string array just as you would concatenate % arrays of any other kind. % % Concatenate two string arrays using square brackets, |[]|. str1 = string({'Mercury','Gemini','Apollo'}); str2 = string({'Skylab','Skylab B','ISS'}); str = [str1 str2] %% % Transpose |str1| and |str2|. Concatenate them and then vertically % concatenate column headings onto the string array. When you concatenate % character vectors into a string array, the character vectors are % automatically converted to strings. str1 = str1'; str2 = str2'; str = [str1 str2]; str = [{'Mission:','Station:'} ; str] %% Append Text to Strings % To append text to strings, use the |plus| operator, |+|. The |plus| operator % appends text to strings but does not change the size of a string array. % % Append a last name to an array of names. If you append a character vector to % strings, then the character vector is automatically converted to a % string. names = string({'Mary';'John';'Elizabeth';'Paul';'Ann'}); names = names + ' Smith' %% % Append different last names. You can append text to a string array from a % string array or from a cell array of character vectors. When you add % nonscalar arrays, they must be the same size. names = string({'Mary';'John';'Elizabeth';'Paul';'Ann'}); lastnames = string({'Jones';'Adams';'Young';'Burns';'Spencer'}); names = names + ' ' + lastnames %% % Append a missing string. When you append a missing string with the plus operator, % the output is a missing string. str1 = string('Jones'); str2 = string(nan); str1 + str2 %% Split, Join, and Sort String Array % MATLAB(R) provides a rich set of functions to work with string arrays. % For example, you can use the |split|, |join|, and |sort| functions to % rearrange the string array |names| so that the names are in % alphabetical order by last name. % % Split |names| on the space characters. Splitting changes |names| from a % 5-by-1 string array to a 5-by-2 array. names = string({'Mary Jones';'John Adams';'Elizabeth Young';'Paul Burns';'Ann Spencer'}); names = split(names) %% % Switch the columns of |names| so that the last names are in the first column. % Add a comma after each last name. names = [names(:,2) names(:,1)]; names(:,1) = names(:,1) + ',' %% % Join the last and first names. The |join| function places a space character % between the strings it joins. After the join, |names| is a 5-by-1 string array. names = join(names) %% % Sort the elements of |names| so that they are in alphabetical order. names = sort(names)