strsplit.m 763 B

1234567891011121314151617181920212223242526272829303132
  1. function f = strsplit(str,pattern)
  2. % function f = strsplit(str,pattern)
  3. %
  4. % <str> is a string
  5. % <pattern> (optional) is a string. default: sprintf('\n').
  6. %
  7. % split <str> using <pattern>. return a cell vector of string fragments.
  8. % note that we generate beginning and ending fragments.
  9. %
  10. % example:
  11. % isequal(strsplit('test','e'),{'t' 'st'})
  12. % isequal(strsplit('test','t'),{'' 'es' ''})
  13. % input
  14. if ~exist('pattern','var') || isempty(pattern)
  15. pattern = sprintf('\n');
  16. end
  17. % find indices of matches
  18. indices = strfind(str,pattern);
  19. % do it
  20. cnt = 1;
  21. f = {};
  22. for p=1:length(indices)
  23. temp = str(cnt:indices(p)-1);
  24. f = [f {choose(isempty(temp),'',temp)}];
  25. cnt = indices(p)+length(pattern);
  26. end
  27. temp = str(cnt:end);
  28. f = [f {choose(isempty(temp),'',temp)}];