English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MATLAB Strings

在MATLAB中创建字符串非常简单。实际上,我们已经使用了很多次。例如,您在命令提示符下键入以下内容-

my_string = 'oldtoolbag.com'

MATLAB将执行上述语句并返回以下结果-

my_string = oldtoolbag.com

MATLAB将所有变量视为数组,而字符串则视为字符数组。让我们使用whos命令来检查上面创建的变量-

whos

MATLAB将执行上述语句并返回以下结果-

Name           Size            Bytes  Class    Attributes
my_string      1x16               32  char

有趣的是,您可以使用数字转换函数,例如uint8uint16以将字符串中的字符转换为其数字代码。char函数将整数向量转换回字符-

在线示例

Create a script file and enter the following code-

my_string = 'w3codebox''s com';
str_ascii = uint8(my_string)        %8位 ascii 值
str_back_to_char= char(str_ascii)  
str_16bit = uint16(my_string)       %16Bit ascii value
str_back_to_char = char(str_16bit)

When running the file, it displays the following result-

str_ascii =
  110  104  111  111  111   39  115   32   99  111  109
str_back_to_char = w3codebox's com
str_16bit =
  110  104  111  111  111   39  115   32   99  111  109
str_back_to_char = w3codebox's com

矩形字符数组

到目前为止,我们讨论的字符串是一维字符数组。但是,我们需要存储更多。我们需要在程序中存储更多维度的文本数据。这是通过创建矩形字符数组来实现的。

创建矩形字符数组的最简单方法是根据需要垂直或水平连接两个或多个一维字符数组。

您可以通过以下两种方式垂直组合字符串-

  • 使用MATLAB连接运算符[],并用分号(;)分隔每一行。请注意,在此方法中,每行必须包含相同数量的字符。对于长度不同的字符串,应根据需要使用空格字符填充。

  • 使用char函数。如果字符串的长度不同,char会用尾随空格填充较短的字符串,以便每行具有相同的字符数。

Example

Create a script file and enter the following code-

doc_profile = ['Zara Ali                             '; ...
               
               'R N Tagore Cardiology Research Center']

                  'RN Tagore Cardiology Research Center')

When running the file, it displays the following result-

doc_profile =
Zara Ali                             
Senior Surgeon                          
R N Tagore Cardiology Research Center
doc_profile =
Zara Ali                            
Senior Surgeon                         
RN Tagore Cardiology Research Center

You can horizontally combine strings in the following two ways-

  • Use MATLAB concatenation operator[]And use commas or spaces to separate input strings. This method retains all trailing spaces in the input array.

  • The strcat function is used to remove trailing spaces from the input.

Example

Create a script file and enter the following code-

name = 'Zara Ali                                                                                         ';
position = 'Sr. Surgeon                                                                                         '; 
worksAt = 'R N Tagore Cardiology Research Center';
profile = [name ', ' position ', ' worksAt]
profile = strcat(name, ', ', position, ', ', worksAt)

When running the file, it displays the following result-

profile = Zara Ali, Senior Surgeon, R N Tagore Cardiology Research Center
profile = Zara Ali, Senior Surgeon, R N Tagore Cardiology Research Center

Merge strings into a cell array.

It can be clearly seen from the previous discussion that it may be麻烦 to merge strings of different lengths, because all strings in the array must have the same length. We used spaces at the end of the strings to make their lengths equal.

However, a more efficient method to combine strings is to convert the result array to a cell array.

MATLAB cell arrays can store different sizes and types of data in an array. Cell arrays provide a more flexible way to store strings of variable lengths.

cellstrThe function converts a character array to a cell array of strings.

Example

Create a script file and enter the following code-

name = 'Zara Ali                                                                                         ';
position = 'Sr. Surgeon                                                                                         '; 
worksAt = 'R N Tagore Cardiology Research Center';
profile = char(name, position, worksAt);
profile = cellstr(profile);
disp(profile)

When running the file, it displays the following result-

{                                                                               
   [1,1] = Zara Ali                                                              
   [2,1] = Sr. Surgeon                                                           
   [3,1] = R N Tagore Cardiology Research Center                                 
}

String functions in MATLAB

MATLAB provides many string functions to create, combine, parse, compare, and operate on strings.

The following table briefly introduces string functions in MATLAB.-

FunctionEffect
Functions used to store text in character arrays, combine character arrays, etc.
blanks

Create a string of blank characters

cellstrCreate a cell array of strings from a character array
char

Convert to a character array (string)

iscellstrDetermine if the input is a cell array of strings
ischarDetermine if an item is an array of character
sprintfFormat data into a string
strcatHorizontally connect strings
strjoinConcatenate strings in a cell array into a single string
Function to identify a part of the string, find and replace a substring
ischarDetermine if an item is an array of character
isletterArray element of a letter
isspaceAs an array element of a space character
isstrpropDetermine if a string belongs to a specified category
sscanfRead formatted data from a string
strfindFind a string within another string
strrepFind and replace substring
strsplitSplit string at specified delimiter
strtokSelected part of the string
validatestringCheck the validity of the text string
symvarDetermine the symbol variables in the expression
regexpMatch regular expression (case-sensitive)
regexpi

Match regular expression (case-insensitive)

regexprepUse regular expression to replace string
regexptranslate

Convert string to regular expression

String comparison functions
strcmpCompare strings (case-sensitive)
strcmpi

Compare strings (case-insensitive)

strncmpCompare the first n characters of a string (case-sensitive)
strncmpi

Compare the first n characters of a string (case-insensitive)

Functions to change string to uppercase or lowercase, create or delete spaces
deblankRemove trailing spaces from the end of string
strtrimRemove leading and trailing spaces from string
lowerConvert string to lowercase
upperConvert string to uppercase
strjustAlign character array

Example

The following examples illustrate some of the string functions mentioned above-

Format string

Create a script file and enter the following code-

A = pi*1000*ones(1,5);
sprintf(' %f \
 %.2f \
%+.2f \
%12.2f \
%012.2f \
', A)

When running the file, it displays the following result-

ans =  3141.592654 
   3141.59 
   +3141.59 
      3141.59 
   000003141.59

Concatenate strings

Create a script file and enter the following code-

% String cell array
str_array = {'red','blue','green', 'yellow', 'orange'};
% Join strings in a cell array into a single string
str1 = strjoin(str_array, ",");-)

str2 = strjoin(str_array, ",");

When running the file, it displays the following result-

str1 = red-blue-green-yellow-orange
str2 = red,blue,green,yellow,orange

Find and replace string

Create a script file and enter the following code-

students = {'Zara Ali', 'Neha Bhatnagar', ...}
            'Monica Malik', 'Madhu Gautam', ...
            'Madhu Sharma', 'Bhawna Sharma', ...
            'Nuha Ali', 'Reva Dutta', ...
            'Sunaina Ali', 'Sofia Kabir';
 
% The strrep function searches for and replaces a substring.
new_student = strrep(students(8), 'Reva', 'Poulomi')
% Display names
first_names = strtok(students

When running the file, it displays the following result-

new_student = 
{
   [1,1]= Poulomi Dutta
}
first_names = 
{
   [1,1]= Zara
   [1,2]= Neha
   [1,3]= Monica
   [1,4]= Madhu
   [1,5]= Madhu
   [1,6]= Bhawna
   [1,7]= Nuha
   [1,8]= Reva
   [1,9]= Sunaina
   [1,10]= Sofia
}

String Comparison

Create a script file and enter the following code-

str1 = 'This is test'
str2 = 'This is text'
if (strcmp(str1, str2))
   sprintf('%s and %s are equal', str1, str2)
else
   sprintf('%s and %s are not equal', str1, str2)
end

When running the file, it displays the following result-

str1 = This is test
str2 = This is text
ans = This is test and This is text are not equal