Sunday, February 14, 2010

split_str_by_comma.m


function ret_cell_array=split_str_by_comma(str)
%
% This function is to split a str by comma, return as cell array
%
% EXAMPLE:
% ret_cell_array=split_str_by_comma('12, 34, 56');
% the ret_cell_array should be {'12','34','56'}
%
% If you have MATLAB, you can use ret_cell_array=regexp(str,',','split') to get job done;
%
%   Copyright 2010 EdgeMe
%   EdgeMe, 10-Feb-2010
%
%

    %find out where are the commas
    commas=regexp(str,',');

    %if no comma, just return the str
    if isempty(commas)
        ret_cell_array={str};
        return;
    else %we found comma(s)

        %first comma, also get rid of space
        ret_cell_array{1}=strrep(str(1:commas(1)-1),' ','');

        for i=1:numel(commas)-1

            ret_cell_array{end+1}=strrep(str(commas(i)+1:commas(i+1)-1),' ','');

        end

        %last one
        if length(str)>commas(end)
            ret_cell_array{end+1}=strrep(str(commas(end)+1:length(str)),' ','');
        end


    end


 end

No comments:

Post a Comment