File: cstrcmp.m

package info (click to toggle)
octave-strings 1.0.5-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 452 kB
  • ctags: 29
  • sloc: makefile: 79; cpp: 67; sh: 25
file content (87 lines) | stat: -rw-r--r-- 2,291 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
## Copyright (C) 2007 Muthiah Annamalai <muthiah.annamalai@uta.edu>
## 
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; If not, see <http://www.gnu.org/licenses/>.
##

## -*- texinfo -*-
## @deftypefn {Function File} @var{rval}= {} cstrcmp(@var{string1},@var{string2})
## compares the  @var{string1} and @var{string2} like the C-library
## function, returning 0 on match, +1 if @var{string1} > @var{string2}
## and -1 if @var{string1} < @var{string2}.
## This operation is asymmetrical. If either @var{string1} or
## @var{string2} are cell-arrays (not both simultaneously), then the
## return value @var{rval} will be a similar cell-array of strings.
##
## @example
## @group
##           cstrcmp('marry','marie') 
##           ##returns value +1
## @end group
## @end example
## @end deftypefn
## @seealso {strcmp}
##


function rval=cstrcmp(s1,s2)
  if nargin < 2
    print_usage();
  end
  v1=iscell(s1);
  v2=iscell(s2);

  if (v1+v2) == 2;
    error(' Only one argument can be a cell-array; see help cstrcmp;');
  end

  if (v1+v2) == 0
    rval=do_cstrcmp(s1,s2);
    return;
  end

  if(v2)
    [s1,s2]=swap(s1,s2);
  end

  L=length(s1);
  rval=zeros(1,L);
  for idx=1:L
    rval(idx)=do_cstrcmp(s1{idx},s2);
  end

  return;
end
%!
%!assert(cstrcmp("hello","hello"),0,0)
%!assert(cstrcmp('marry','marie'),+1,0)
%!assert(cstrcmp('Matlab','Octave'),-1,0)
%!assert(cstrcmp('Matlab',{'Octave','Scilab','Lush','Yorick'}),[-1,-1,+1,-1],[])
%!assert(cstrcmp({'Octave','Scilab','Lush','Yorick'},'Matlab'),[+1,+1,-1,+1],[])
%!

function v=do_cstrcmp(s1,s2)
 L2=length(s2);
 L1=length(s1);
 L=min(L1,L2);
 for idx=1:L
   p=s1(idx);
    q=s2(idx);
    if ( p ~= q )
     v=sign(p-q);
     return
   end
 end
 v=sign(L1-L2);
 return	   
end