home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / octa21eb.zip / octave / SCRIPTS.ZIP / scripts.fat / strings / findstr.m < prev    next >
Text File  |  1999-04-29  |  2KB  |  88 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. ## usage: findstr (s, t [, overlap])
  21. ##
  22. ## Returns the vector of all positions in the longer of the two strings
  23. ## S and T where an occurence of the shorter of the two starts.
  24. ##
  25. ## If the optional argument OVERLAP is nonzero, the returned vector
  26. ## can include overlapping positions (this is the default).
  27. ##
  28. ## For example,
  29. ##
  30. ##   findstr ("abababa", "aba")     =>  [1, 3, 5]
  31. ##   findstr ("abababa", "aba", 0)  =>  [1, 5]
  32.  
  33. ## Author: Kurt Hornik <Kurt.Hornik@ci.tuwien.ac.at>
  34. ## Adapted-By: jwe
  35.  
  36. function v = findstr (s, t, overlap)
  37.  
  38.   if (nargin < 2 || nargin > 3)
  39.     usage ("findstr (s, t [, overlap])");
  40.   endif
  41.  
  42.   if (nargin == 2)
  43.     overlap = 1;
  44.   endif
  45.  
  46.   if (isstr (s) && isstr (t))
  47.  
  48.     ## Make S be the longer string.
  49.  
  50.     if (length (s) < length (t))
  51.       tmp = s;
  52.       s = t;
  53.       t = tmp;
  54.     endif
  55.  
  56.     s = toascii (s);
  57.     t = toascii (t);
  58.  
  59.     l_t = length (t);
  60.  
  61.     ind = 1 : l_t;
  62.     limit = length (s) - l_t + 1;
  63.     v  = zeros (1, limit);
  64.     i = 0;
  65.  
  66.     k = 1;
  67.     while (k <= limit)
  68.       if (s (ind + k - 1) == t)
  69.     v (++i) = k;
  70.     if (! overlap)
  71.       k = k + l_t - 1;
  72.     endif
  73.       endif
  74.       k++;
  75.     endwhile
  76.  
  77.     if (i > 0)
  78.       v = v (1:i);
  79.     else
  80.       v = [];
  81.     endif
  82.  
  83.   else
  84.     error ("findstr: expecting first two arguments to be strings");
  85.   endif
  86.  
  87. endfunction
  88.