10

Is there a (default) Matlab function that behaves similar to the java method split(delimiter), where you can tokenize a string based on an arbritary delimiter?

Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
robguinness
  • 16,266
  • 14
  • 55
  • 65
  • 3
    Worth mentioning that as of Matlab 2013a there is a function called `strsplit` that does it. – Dan Mar 04 '14 at 11:25

3 Answers3

17

There is a built-in function called textscan that's capable of this:

>> C = textscan('I like stack overflow', '%s', 'delimiter', 'o');    
>> C = C{1}

C = 
    'I like stack '
    'verfl'
    'w'
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
  • just saying - `strtok{}` seemed nicer. – AruniRC Oct 10 '12 at 09:28
  • suppose the string `str = 'myfile.txt'` and we want to separate it on the `.` delimiter. So `(str0,str1) = strtok(str,'.')` would split the string on the delimiter specified in the second argument to 'strtok()`. The curly braces in the prev comment were a typo, sorry. – AruniRC Oct 11 '12 at 18:07
  • 2
    @AruniRC: true. However, it only splits *once*, e.g., to achieve the split shown in my answer, you'd have to recursively call `strtok`, whereas the `textscan` solution is a oneliner (OK, 2, but oh well :) – Rody Oldenhuis Oct 11 '12 at 18:13
  • ah. always assumed (wrongly) that `strtok` would work for multiple-delimiters. so then - nice solution? :) – AruniRC Oct 12 '12 at 11:51
6

Here are more than one ways to split a string. One as Rody Oldenhuis has just mentioned, and here are some others:

1> Using the function regexp :

>> str = 'Good good study Day day up';
>> regexp(str,'\s','split')
ans = 
    'Good'    'good'    'study'    'Day'    'day'    'up'
>> 

2> Using the function strread:

>> str = 'Section 4, Page 7, Line 26';
>> strread(str, '%s', 'delimiter', ',')
ans = 
    'Section 4'
    'Page 7'
    'Line 26'
>> 
Eastsun
  • 18,526
  • 6
  • 57
  • 81
2

There is a function similar to what you mentioned on file exchange in a package called xml_toolbox.

It is called strsplit.

strsplit('I like stack overflow','o')

ans =

'I like stack' 'verfl' 'w'

Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104