Matlab的优势在于向量操作,字符串操作往往费时费力,但是如果能充分利用Matlab自带的一些函数,也可以取得不错的效果。下面就介绍一下字符串数组查找的小技巧。

  字符串数组我通常会选择应用cell格式保存,下面的分析也是建立在这个前提下。

  

  【1】 strcmp() 函数

  strcmp() 函数的基本功能是比较两个字符串是否相等,其基本用法是:

1 TF = strcmp(s1,s2);

  但是,如果我们要查找字符串数组中等于某字符串的索引时,该如果操作?strcmp() 函数也提供了这个功能,用法相同:

1 TF = strcmp(s1,s2);

  其中,s1是字符串数组,s2是字符串,返回值为逻辑类型,大小与字符串数组s1相同;

  【2】 strfind() 函数

  strcmp() 函数比较的是两个字符串是否相等。但是如果想查找字符串数组中包含某字符串的记录时,我们就可以选择strfind() 函数。

1 k = strfind(str,pattern);

  输出结果k表示pattern在str中出现的位置,若不出现,则返回[]。比如:

1 S = ‘Find the starting indices of the pattern string’;
2 k = strfind(S, ‘in’)
3 k = 
4     2    15    19    45

  上面是strfind() 函数的基本功能,但是如果查找字符串数组中包含某字符串的索引时,strfind() 函数也可以大显身手,返回和字符串数组相同大小的cell类型数据,每个cell为字符串出现位置,向量类型,比如:

Matlab 字符串比较
    


            
http://www.cnblogs.com/anzhiwu815/p/5885097.html
 1 cstr = {‘How much wood would a woodchuck’; ‘if a woodchuck could chuck wood?’};
 2 idx = strfind(cstr, ‘wood’)
 3 idx = 
 4     [1*2 double]
 5     [1*2 double]
 6 Idx{:,:}
 7 ans = 
 8     10    23
 9 ans =
10     6    28
Matlab 字符串比较
    


            
http://www.cnblogs.com/anzhiwu815/p/5885097.html

  【3】 一个问题:有一个字符串数组cstr1,要找到包含字符串str2的索引,该如果操作?

  一个直接的答案是:

Matlab 字符串比较
    


            
http://www.cnblogs.com/anzhiwu815/p/5885097.html
1 idx = strfind(cstr1,str2);
2 finger(length(idx),1) = 1==0;
3 for i = 1:length(idx)
4     if ~isempty(idx(i))
5         finger(i) = 1==1;
6     end
7 end
Matlab 字符串比较
    


            
http://www.cnblogs.com/anzhiwu815/p/5885097.html

  思路是正确的,但是代码量有点大,需要7行,而且速度较慢。其实要实现这个功能,1行代码足矣。如下:

1 finger = ~cellfun(@isempty, strfind(cstr1,str2));

  上面的代码还有另外一种写法,

1 finger = cellfun(@(x) ~isempty(strfind(x,str2)), cstr1);

  三种方法输出结果是一样的,但是第2种方法速度最快,第1种方法次之,第3种方法最慢。大家可以进行测试下。

相关文章:

  • 2022-01-15
  • 2021-07-14
  • 2021-11-01
  • 2021-10-08
  • 2021-11-26
  • 2021-05-19
  • 2021-07-01
  • 2022-01-10
猜你喜欢
  • 2021-05-22
  • 2021-11-28
  • 2021-04-11
  • 2022-01-06
  • 2021-12-19
  • 2022-01-13
相关资源
相似解决方案