home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / octa21fb.zip / octave / SCRIPTS.ZIP / scripts.fat / strings / findstr.m < prev    next >
Text File  |  1999-12-24  |  2KB  |  90 lines

  1. ## Copyright (C) 1996 Kurt Hornik
  2. ##
  3. ## This file is part of Octave.
  4. ##
  5. ## Octave is free software; you can redistribute it and/or modify it
  6. ## under the terms of the GNU General Public License as published by
  7. ## the Free Software Foundation; either version 2, or (at your option)
  8. ## any later version.
  9. ##
  10. ## Octave is distributed in the hope that it will be useful, but
  11. ## WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13. ## General Public License for more details.
  14. ##
  15. ## You should have received a copy of the GNU General Public License
  16. ## along with Octave; see the file COPYING.  If not, write to the Free
  17. ## Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  18. ## 02111-1307, USA.
  19.  
  20. ## -*- texinfo -*-
  21. ## @deftypefn {Function File} {} findstr (@var{s}, @var{t}, @var{overlap})
  22. ## Return the vector of all positions in the longer of the two strings
  23. ## @var{s} and @var{t} where an occurrence of the shorter of the two starts.
  24. ## If the optional argument @var{overlap} is nonzero, the returned vector
  25. ## can include overlapping positions (this is the default).  For example,
  26. ## 
  27. ## @example
  28. ## findstr ("ababab", "a")
  29. ##      @result{} [ 1, 3, 5 ]
  30. ## findstr ("abababa", "aba", 0)
  31. ##      @result{} [ 1, 5 ]
  32. ## @end example
  33. ## @end deftypefn
  34.  
  35. ## Author: Kurt Hornik <Kurt.Hornik@ci.tuwien.ac.at>
  36. ## Adapted-By: jwe
  37.  
  38. function v = findstr (s, t, overlap)
  39.  
  40.   if (nargin < 2 || nargin > 3)
  41.     usage ("findstr (s, t [, overlap])");
  42.   endif
  43.  
  44.   if (nargin == 2)
  45.     overlap = 1;
  46.   endif
  47.  
  48.   if (isstr (s) && isstr (t))
  49.  
  50.     ## Make S be the longer string.
  51.  
  52.     if (length (s) < length (t))
  53.       tmp = s;
  54.       s = t;
  55.       t = tmp;
  56.     endif
  57.  
  58.     s = toascii (s);
  59.     t = toascii (t);
  60.  
  61.     l_t = length (t);
  62.  
  63.     ind = 1 : l_t;
  64.     limit = length (s) - l_t + 1;
  65.     v  = zeros (1, limit);
  66.     i = 0;
  67.  
  68.     k = 1;
  69.     while (k <= limit)
  70.       if (s (ind + k - 1) == t)
  71.     v (++i) = k;
  72.     if (! overlap)
  73.       k = k + l_t - 1;
  74.     endif
  75.       endif
  76.       k++;
  77.     endwhile
  78.  
  79.     if (i > 0)
  80.       v = v (1:i);
  81.     else
  82.       v = [];
  83.     endif
  84.  
  85.   else
  86.     error ("findstr: expecting first two arguments to be strings");
  87.   endif
  88.  
  89. endfunction
  90.