home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / octa21fb.zip / octave / SCRIPTS.ZIP / scripts.fat / strings / split.m < prev    next >
Text File  |  1999-12-24  |  2KB  |  89 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} {} split (@var{s}, @var{t})
  22. ## Divides the string @var{s} into pieces separated by @var{t}, returning
  23. ## the result in a string array (padded with blanks to form a valid
  24. ## matrix).  For example,
  25. ## 
  26. ## @example
  27. ## split ("Test string", "t")
  28. ##      @result{} "Tes "
  29. ##         " s  "
  30. ##         "ring"
  31. ## @end example
  32. ## @end deftypefn
  33.  
  34. ## Author: Kurt Hornik <Kurt.Hornik@ci.tuwien.ac.at>
  35. ## Adapted-By: jwe
  36.  
  37. function m = split (s, t)
  38.  
  39.   if (nargin != 2)
  40.     usage ("split (s, t)");
  41.   endif
  42.  
  43.   if (isstr (s) && isstr (t))
  44.  
  45.   l_s = length (s);
  46.   l_t = length (t);
  47.  
  48.   if (l_s == 0)
  49.     m = "";
  50.     return;
  51.   elseif (l_s < l_t)
  52.     error ("split: s must not be shorter than t");
  53.   endif
  54.  
  55.   if (l_t == 0)
  56.     ind = 1 : (l_s + 1);
  57.   else
  58.     ind = findstr (s, t, 0);
  59.     if (length (ind) == 0)
  60.       m = s;
  61.       return;
  62.     endif
  63.     ind = [1 - l_t, ind, l_s + 1];
  64.   endif
  65.  
  66.   cmd = "";
  67.  
  68.   limit = length (ind) - 1;
  69.  
  70.   for k = 1 : limit
  71.  
  72.     range = (ind (k) + l_t) : ind (k + 1) - 1;
  73.  
  74.     if (k != limit)
  75.       cmd = sprintf ("%s\"%s\", ", cmd, undo_string_escapes (s (range)));
  76.     else
  77.       cmd = sprintf ("%s\"%s\"", cmd, undo_string_escapes (s (range)));
  78.     endif
  79.  
  80.   endfor
  81.  
  82.   m = eval (sprintf ("str2mat (%s);", cmd));
  83.  
  84.   else
  85.     error ("split:  both s and t must be strings");
  86.   endif
  87.  
  88. endfunction
  89.