问题描述
在matlab中,我们有时需要对字符串数组进行分类、筛选等,我们可以通过以下代码实现。
代码复现
例题一
要判断一个 cell 数组中是否包含特定的单词(字符串),你可以使用循环遍历每个 cell 元素,并使用字符串处理函数来判断每个单元格中是否包含该单词。以下是一个示例:
% 创建一个包含字符串的 cell 数组
cellArray = {'This is a sample string.', 'Another cell.', 'No c here.', 'Contains c.'};
wordToFind = 'c';
% 初始化一个标志变量
found = false;
% 遍历每个 cell 元素
for i = 1:numel(cellArray)
if contains(cellArray{i}, wordToFind)
found = true;
break; % 一旦找到,就可以退出循环
end
end
if found
disp('The word c is present in the cell array.');
else
disp('The word c is not present in the cell array.');
end
例题二
我们将FileNames进行分类,区分出包含c和d字符串数组。
FileNames如图所示。
n = length(FileNames);
cc=0;
dd=0;
FileNamesc={};
FileNamesb={};
for ii=1:n
tem1= FileNames(ii);
wordToFind = 'c';
found = false;
for i = 1:numel(tem1)
if contains(tem1{i}, wordToFind)
found = true;
break;
end
end
if found
cc=cc+1;
FileNamesc(cc,1)=FileNames(ii);
else
dd=dd+1;
FileNamesb(dd,1)=FileNames(ii);
end
end
注释:
1.定义cell数组FileNamesc={},数值数组定义为格式为:FileNamesc=[]。
2.tem1= FileNames(ii);取第
i
i
ii
ii个元素进行判断。
3.wordToFind = ‘c’;为区分的元素。
4.FileNamesc(cc,1)=FileNames(ii);cell数组和cell数组之间转化用(),cell转化为double用{}。
eg: