split a string by each / in matlab

To split a string in Matlab using forward slash as delimiter, you can use the strsplit function. Here's an example:

main.m
myStr = 'this/is/a/sample/string';
myCellArray = strsplit(myStr, '/');
71 chars
3 lines

The output myCellArray will be a cell array with each word separated by forward slash:

main.m
myCellArray = 
{
  [1,1] = this
  [1,2] = is
  [1,3] = a
  [1,4] = sample
  [1,5] = string
}
93 chars
9 lines

If you have a string array, stringArray, you can split each of its elements using a for loop like this:

main.m
stringArray = ["this/is", "another/sample/string"];
for i = 1:numel(stringArray)
   myCellArray{i} = strsplit(stringArray(i), '/');
end
136 chars
5 lines

The output will be a cell array with each element containing the split strings:

main.m
myCellArray = 
{
  [1,1] = {
      [1,1] = this
      [1,2] = is
    }
  [1,2] = {
      [1,1] = another
      [1,2] = sample
      [1,3] = string
    }
}
155 chars
13 lines

related categories

gistlibby LogSnag