A string, also known as a character array, is formed by connecting multiple characters. In MATLAB, strings are generally enclosed in single quotes ('').
Creating Strings
You can specify character data by placing characters inside single quotes.
[Example 2-32] Create a 1×5 string country.
country = 'China';
Enter the whos command in the Command Window, the output shows:
Name Size Bytes Class
country 1x5 10 char
From the above results, it can be seen that in memory, each character occupies two bytes.
Use the class function and ischar function to test the data type of country below, the result shows it is a string.
class(country)
ans =
char
ischar(country)
ans =
1
Creating Two-Dimensional Strings
When creating a two-dimensional string, you should ensure that each row has the same length.
[Example 2-33] Create a two-dimensional string.
The following two strings both have 5 characters, you can combine them into a two-dimensional string.
name = ['Li Yi'; 'Hu Xu']
name =
Li Yi
Hu Xu
When creating strings from different lengths, pad the shorter string with spaces at the end to make all strings the same length. Such as:
name = ['Liu Ying'; 'Hu Xu '];
Using the char function to create a string array is simpler; the char function automatically pads with spaces based on the length of the longest input string.
[Example 2-34] Use the char function to create a string array.
Enter in the Command Window:
name = char('Liu Ying','Hu Xu')
name =
Liu Ying
Hu Xu
[Example 2-35] Use the deblank function to remove trailing spaces when extracting strings from an array.
Enter in the Command Window:
trimname = deblank(name(2,:))
trimname =
Hu Xu
size(trimname)
ans =
1 5
Type Conversion
[Example 2-36] Use the char function to convert a cell array into a standard string array.
Enter in the Command Window:
celldata={'Sun junfang','NewStudent','Beijing'};
strings = char(celldata)
strings =
Sun junfang
NewStudent
Beijing
length(strings(3,:))
ans =
11
[Example 2-37] The str2double function converts a string cell array into double-precision values represented by strings.
Enter in the Command Window:
c = {'37.294e-1'; '-58.375'; '13.796'};
d = str2double(c)
d =
3.7294
-58.3750
13.7960
whos
Name Size Bytes Class
c 3x1 380 cell
d 3x1 24 double
Grand total is 28 elements using 248 bytes
[Example 2-38] The int2str function converts integer data into string type data.
Enter in the Command Window:
x=2003;
y = int2str(x);
size(y)
ans =
1 4
It can be seen that the int2str function converts scalar x into a 1×4 vector containing the string "2003".
[Example 2-39] The num2str function provides more control over the output string format. The second variable of this function is optional, used to set the number of digits of the output string or specify an actual format.
Enter in the Command Window:
p = num2str(pi,6)
p =
3.14159
The mat2str function can convert an array to a string.
[Example 2-40] Create a 2×3 array A.
A = [1 2 3; 4 5 6]
A =
1 2 3
4 5 6
[Example 2-41] The mat2str function returns a string containing text. Entering this text in the command line is used to create matrix A.
Enter in the Command Window:
B = mat2str(A)
B =
[1 2 3; 4 5 6]
Comparing Strings
[Example 2-42] Use the strcmp function to compare strings.
Enter in the Command Window:
str1 = 'hello';
str2 = 'help';
strcmp(str1,str2)
ans =
0
Since str1 and str2 are not equal, the strcmp function returns 0 (false) when called.
Using the strncmp function, you can compare the first n+1 characters of strings, such as:
C = strncmp(str1,str2,2)
C =
1
Since the first three characters of "hello" and "help" are the same, the result returns 1 after calling the strncmp function.
[Example 2-43] For these string structure arrays below, you can use some functions to compare them one cell at a time.
A = {'book';'pen';'rule'};
B = {'pencil';'pen';'pencilbox'};
Compare using the strcmp function below:
strcmp(A,B)
ans =
0
1
0
strncmp(A,B,1)
ans =
0
1
0
For strings, you can use MATLAB's relational operators to compare.
[Example 2-44] Use == below to determine the same characters in two strings.
A = 'face';
B = 'cake';
A == B
ans =
0 1 0 1
All relational operators (>, >=, <, <=, ==, !=) compare the values of corresponding characters.
Concatenating Strings
Strings can usually be concatenated from smaller elements. The two general methods for concatenation are using the MATLAB concatenation operator ([]) or the sprintf function.
[Example 2-45] The second and third lines below demonstrate these two methods, which will give the same result:
num_chars = 28;
s = ['字符个数为:' int2str(num_chars) ]
s = sprintf('有 %d 个字符\n', num_chars)
[Example 2-46] You can also combine two or more strings together using the strcat function.
Enter in the Command Window:
country = 'China';
province= 'SiChuan';
strcat(country,',',province)
ans =
China,SiChuan
Note: When creating strings using concatenation methods, using the sprintf function is better than using [] because it is more readable, especially when composing complex expressions. This function allows more control over the output format and generally runs faster. You can also use strcat to concatenate strings, but for simple concatenation, using sprintf and [] runs faster.
Character Classification
There are two functions that can classify characters in a string:
The isletter function determines if a character is a letter;
The isspace function determines if a character is a whitespace character (space, tab, or newline).
[Example 2-47] Use the isletter function to create a string named mystring.
mystring = 'Room 401';
A = isletter(mystring)
A =
1 1 1 1 0 0 0 0
The first four characters are letters, so the return value is 1.
Search and Replace
MATLAB provides several functions for searching and replacing strings.
[Example 2-48] Use strrep and findstr functions to operate on strings.
For the string label:
label = 'Sample 1, ';
Use the strrep function for standard search and replace operations below, using strrep to change "04/28" to "04/30".
newlabel = strrep(label,'28','30')
newlabel =
Sample 1,
Use the findstr function below to return the starting position of a substring into a longer string.
position = findstr('amp',label)
position =
2
The starting position of the string 'amp' in the label string is the 2nd character position in the label string.
The strtok function returns the characters before the first delimiter found in the input string. This function can be used to separate sentences into words.
[Example 2-49] The strmatch function searches in rows of a string or string cell array to see if there are strings starting with a given character sequence. It returns the row numbers of rows starting with that string.
Enter in the Command Window:
maxstrings = strvcat('max','minimax','maximum')
maxstrings =
max
minimax
maximum
strmatch('max',maxstrings)
ans =
1
3
Since in the maxstrings string cell array, the 1st and 3rd rows start with 'max', the return value from the strmatch function is 1 and 3.