• split_str: Split a string based on an array of character delimiters in Matlab

    by  • January 14, 2009 • matlab • 2 Comments

    I recently needed to do some processing of some data in a text file within matlab where I needed to break up a given string based upon a number of delimiters. I produced the following function which can be used in MATLAB to split a string into a cell array of strings based upon a character array of delimiters:

    function parts = split_str(splitstr, str)
    %split_str Split a string based upon an array of character delimiters
    %   split_str(splitstr, str) splits the string STR at every occurrence
    %   of an array of characters SPLITSTR and returns the result as a cell
    %   array of strings.
    %   usage: split_str(['_';','],'hi,there_how,you_doin?')
    %   ans =
    %    'hi'    'there'    'how'    'you'    'doin?'
       nargsin = nargin;
       error(nargchk(2, 2, nargsin));
       splitlen = 1;  %char's of length 1
       parts = {};
       k=[];           %empty array holding indexes of where to split
       last_split = 1; %index of last split
          for x=1:length(splitstr)
              k = [k strfind(str, splitstr(x))];     %combines all the found indexes
          k = sort(k);   %sorts out indexes
          if isempty(k)
             parts{end+1} = str;
          for x=1:length(k)
              parts{end+1} = str(last_split : k(x)-1);
              last_split = k(x)+1;
          %now add the final string to the result
          parts{end+1} = str(last_split : length(str));


    .NET developer at thetrainline.com, previously web developer at MRM Meteorite. Awarded a PhD in misbehaviour detection in wireless ad-hoc networks.A keen C# ASP.net developer bridging the gap with APIs and JavaScript frameworks, one web app at a time.


    2 Responses to split_str: Split a string based on an array of character delimiters in Matlab

    1. Tim
      July 7, 2009 at 1:30 pm

      Couldn’t you just write this?


      You would have to escape any metacharacters, but still….

    2. July 10, 2009 at 10:14 am

      thanks – thats much more concise!


    Leave a Reply

    Your email address will not be published. Required fields are marked *