在Matlab中查找另一个字符串中的字符串

时间:2015-05-21 12:00:33

标签: string matlab

我必须创建一个带有两个输入的函数:一个字符串的单元格数组(让我们称之为txt)和一个字符串(让我们称之为str )。该函数必须删除其字符串与txt相同或包含str作为子字符串的单元格向量str的每个元素。 目前我尝试过以下内容:

function c = censor( txt,str )
    c = txt;
    n = length(c);
    for i = 1:n
        a = c{ i };
        a( a == str ) = [];
        c{i} = a;
    end
end

但它不起作用,它会给出错误Matrix dimensions must agree.我理解可能是因为str有多个角色,但我不知道怎么做查找单元格数组str的任何字符串中是否包含txt

1 个答案:

答案 0 :(得分:3)

正如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和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
相关问题