使用strrep删除字符串

时间:2012-12-17 19:39:25

标签: string matlab

我是MATLAB脚本的新手。我有一个要删除的字符串,该字符串来自数组结构文件。要删除的字符串在每个循环中都不同。 CanI将更改字符串存储在变量中并使用变量strrep删除该字符串?例如:

%% string i want to delete is "is_count_del=auto;"
delstrng=is_count_del_auto;
%%filetext is the name of the file from which is_count_del=auto; is to be deleted
r=strrep(filetext,'delstrng','');

我想我没有正确使用strrep。如何实现预期的结果?

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你可以:

% open file to be filtered and output file
fin = fopen('file-to-be-filtered.txt');
fout = fopen('output-file.txt');

% for every line of a file-to-be-filtered ...
tline = fgets(fin);
while ischar(tline)
    % ... filter for all possible patterns        
    for delstring % -> delstring iterates over all patterns
        tline = strrep(tline, delstrng, '');
    end

    % save filtered line to file
    fprintf(fout, tline);

    % get next line
    tline = fgets(fin);
end

答案 1 :(得分:1)

strrep可以应用于单元格数组,因此这使您的工作变得非常简单:

% # Read input file
C = textread('input.txt', '%s', 'delimiter', '\n');

% # Remove target string
C = strrep(C, 'is_count_del=auto', '');

% # Write output file
fid = fopen('output.txt', 'w');
for ii = 1:numel(C)
    fprintf(fid, '%s\r\n', C{ii});
end
fclose(fid)