Question

How can I split a string into a list of substrings, where the delimiter to split by is a MATLAB object type?

For example:

>> splitByType('a1b2c3',type=integer)
['a','b','c']

or:

>> splitByType('a1b2c3',type=character)
['1','2','3']
Was it helpful?

Solution

I'm not sure what you mean by MATLAB object type. For integers, you can use:

a='a1b2c'
regexp(a,'[0-9]+','split')

which outputs:

ans = 

    'a'    'b'    'c'

Another alternative is:

regexp(a,'\d+','split')

OTHER TIPS

You're looking for regexp() by passing the corresponding regular expression of the type:

  • For integers: regexp('a1b2c','\d+','split') % or use '[0-9]+'
  • For characters: regexp('a1b2c','[a-z]+','split')

I'd go with the regexp answer, if you are comfortable with regular expressions, but you can also use strsplit with a cell array of strings containing the possible delimiters:

strsplit(a,cellstr(num2str((0:9)'))')        % digits
strsplit(a,cellstr(char([65:90 97:122])')')  % word characters

Also, strsplit has a regular expression mode (bizarre! why would you use this over regexp?):

strsplit(a,'\d+','delim','reg')  % one or more digits
strsplit(a,'\w+','delim','reg')  % one or more word characters

Which are equivalent to regexp(a,'\d+','split') and regexp(a,'\w+','split').

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top