正如Anders指出的那样,您希望使用strfind
来查找其他字符串内部的字符串。这是您可以编写函数的一种方式。基本上整个应用strfind
整个txt
单元阵列,然后删除有匹配的条目。
代码:
function censor(txt,str)
clc
clear
%// If no input are supplied..demo
if nargin ==0
str = 'hello';
txt = {'hellothere' 'matlab' 'helloyou' 'who are you' 'hello world'};
end
IsItThere = strfind(txt,str)
现在IsItThere
是一个单元阵列与一些1和空单元格:
IsItThere =
[1] [] [1] [] [1]
让我们填补空白单元格为0,所以我们可以在以后进行逻辑索引:
IsItThere(cellfun('isempty',IsItThere))={0}
在其中找到一个匹配发生索引:
个
IndicesToRemove = find(cell2mat(IsItThere))
IndicesToRemove =
1 3 5
并卸下电池:
txt(IndicesToRemove) = [];
txt
现在看起来是这样的:
txt =
'matlab' 'who are you'
end
如果你喜欢,你可以结合几个步骤在一起,但我希望是很清晰: )
这里是整个代码,您可以在.m文件复制/粘贴:
function censor(txt,str)
clc
clear
%// If no input are supplied..demo
if nargin ==0
str = 'hello';
txt = {'hellothere' 'matlab' 'helloyou' 'who are you' 'hello world'};
end
IsItThere = strfind(txt,str)
IsItThere(cellfun('isempty',IsItThere))={0}
IndicesToRemove = find(cell2mat(IsItThere))
txt(IndicesToRemove) = [];
txt
end
看看strfind。 http://se.mathworks.com/help/matlab/ref/strfind.html –
不错,它做我需要的,但问题是当巧合出现不止一次。一旦找到所有的巧合,我不知道如何去除每个元素。 – Hec46