MATLAB Answers

0

Is there an efficient method to remove leading underscores from a cell array of strings?

Asked by Ken Campbell on 6 Aug 2014
Latest activity Commented on by Ken Campbell on 6 Aug 2014
Given
a={'rose','_tulip_blue','lilac','_daisy'}
is there an efficient way of stripping the leading underscores to give
b={'rose','tulip_blue','lilac','daisy'}
I tried
strtok(a,'_')
but that gives
b={'rose','tulip','lilac','daisy'}
and misses the '_blue'. I would like to avoid looping through the strings one at a time if possible.

  0 Comments

Sign in to comment.

2 Answers

Answer by Adam
on 6 Aug 2014
 Accepted Answer

[b, c] = strtok( a, '_' )
b = strcat( b, c )
looks like it works.

  1 Comment

I agree it works :-)
It also copes with more than 2 underscores. For example.
a={'rose','_tulip_blue_red','lilac','_daisy'}
[b,c]=strtok(a,'_');
b=strcat(b,c);
gives
b={'rose' 'tulip_blue_red' 'lilac' 'daisy'}
Thanks

Sign in to comment.


Answer by AJ von Alt
on 6 Aug 2014

b = regexprep(a,'^_','','emptymatch')

  1 Comment

That works too and is elegant. I should learn more about regular expressions. Thanks.

Sign in to comment.