splitting strings?

Matthias Brennwald matthias at brennwald.org
Tue Feb 3 01:23:42 CST 2009


On Feb 2, 2009, at 9:13 PM, Thomas Treichl wrote:

> Matthias Brennwald schrieb:
>> Dear all
>> I used the 'split' command to split stings in Octave. However,  
>> running  this code in Matlab results in an error saying that  
>> 'split' is unknown  to Matlab. Is there an alternative that works  
>> on both Octave and Matlab?
>
> Hi Matthias,
>
> on a 3.0.3 system you can test if the strtok function can be used  
> for your needs, type "help strtok" to get an explanation for this  
> function. The split example from the help message rewritten with the  
> strtok function is
>
>  N = 2;
>  vstr = "Test string";
>
>  for vcnt = 1:N
>    [vres{vcnt}, vstr] = strtok (vstr, "t");
>  endfor
>
>  vres{end} = [vres{end}, vstr];
>  vres
>
> or without N, something like
>
>  vstr = "Test string";
>  vcnt = 1;
>
>  while (~isempty (vstr))
>    [vres{vcnt}, vstr] = strtok (vstr, "t");
>    vcnt = vcnt + 1;
>  endwhile
>
>  vres{end} = [vres{end}, vstr];
>  vres
>
> Best regards,
>
>  Thomas

Thanks!

The second example did the trick (the first seems to loose the last  
part of the initial string). I had to modify the code a bit to make it  
work with Matlab too. Just for the record, this is it:

--------
  vstr = sprintf ('Cars suck\tMotorbikes too\tBicycles are way cool!');
  vcnt = 1;

  while (~isempty (vstr))
    [vres{vcnt}, vstr] = strtok (vstr, sprintf ('\t'));
    vcnt = vcnt + 1;
  end

  vres{end} = [vres{end}, vstr];
  vres
--------

Matthias


More information about the Help-octave mailing list