Matlab替换特定字符串

2025-10-14 08:19:28

1、这里介绍matlab的字符串处理函数,findstr,strrep,strtok,strmatch命令。

Matlab替换特定字符串

2、首先介绍findstr:

先做一个字符串数组:

a = 'this is an example.';

然后在a中找出相应的字符或字符串:

bb = findstr(a,'is');

返回值bb为字符串is中第一个字母在a中的位置。

Matlab替换特定字符串

3、下一个介绍strrep:

strrep是使用新的字符串替换已有的字符串。

Matlab替换特定字符串

4、strtok主要用于一个一个提取字符串中的字符,应该是以空格为单位:

在上述命令的基础上,输入如下命令:

stok = a;for jj = 1:4[sstok,stok] = strtok(stok);sstokend

得到的结果如下:

Matlab替换特定字符串

5、strmatch命令:即找出字符串char或元胞数组中与给出字符串相同的数组。

在未指定是否准确相同时,只匹配与给出字符串相同大小前几个数据,如果要求准确匹配,就是说size也要相同。

Matlab替换特定字符串

Matlab替换特定字符串

6、下面给出一个function,可以替换文本中想要替换的字符串。

%%%%%%%% this file was used to replace a string with a new one;function replacement(filename,old_str,new_str)%%% filename was the file of the string which was changed;%%% old_str was the string which you want to change.%%% new_str was the string which you want to change to.%%% the changed file will be saved in another file which %%% the name will be renamed as 'new_file.dat';fid = fopen(filename,'r');while feof(fid) == 0    tline = fgetl(fid);    tline01 = strrep(tline,old_str,new_str);    ffid = fopen('new_file.dat','a+');    fprintf(ffid,'%s\n',tline01);    fclose(ffid);endfclose(fid);

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢