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?

1
  • 3
    Worth mentioning that as of Matlab 2013a there is a function called strsplit that does it.
    – Dan
    Mar 4, 2014 at 11:25

3 Answers 3

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'
4
  • just saying - strtok{} seemed nicer.
    – AruniRC
    Oct 10, 2012 at 9: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, 2012 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 :) Oct 11, 2012 at 18:13
  • ah. always assumed (wrongly) that strtok would work for multiple-delimiters. so then - nice solution? :)
    – AruniRC
    Oct 12, 2012 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'
>> 
1
  • @robguinness Works fine in mine. Anyway, the function 'regexp' is better.
    – Eastsun
    Aug 29, 2012 at 10:25
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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.