## Flipping specific segment of string rather than the whole string

### Samiha Shimla (view profile)

on 17 Jan 2019
Latest activity Commented on by Samiha Shimla

### Samiha Shimla (view profile)

on 17 Jan 2019
If I have a string
str='One two buckle my shoe'
how can I flip it to look as follows?
strM='enO owt elkcub ym eohs'
I have tried using 'flip' and 'reverse' in a few different ways but every time I get
strN='eohs ym elkcub owt enO'

Jan

### Jan (view profile)

on 17 Jan 2019
This sounds like a homework question. Please mention this explicitly, because then we can help you to solve the problem by your own. This is better than submitting a solution written by someone else.
Samiha Shimla

### Samiha Shimla (view profile)

on 17 Jan 2019
Hey, rest assured this is not homework. It is a section of a past paper I am solving. I was specifically struggling with this bit. Thanks for the help!

### Stephen Cobeldick (view profile)

on 17 Jan 2019

regexprep(str,'\w+','\${fliplr(\$0)}')

Jan

### Jan (view profile)

on 17 Jan 2019
+1. Compact and clear!
Sean de Wolski

### Sean de Wolski (view profile)

on 17 Jan 2019
Nice use of a function in a regexp!

on 17 Jan 2019

on 17 Jan 2019

str='One two buckle my shoe';
b=strsplit(str,' ');
strM=strjoin(cellfun(@flip,b,'un',0))
b=flip(strsplit(str,' '));
strN=strjoin(cellfun(@flip,b,'un',0))
Gives:
str =
'One two buckle my shoe'
strM =
'enO owt elkcub ym eohs'
strN =
'eohs ym elkcub owt enO'

Show 1 older comment

on 17 Jan 2019
>> b=strsplit(str,' ') % splits the string as cell arrays when there is space in between words
b =
1×5 cell array
{'One'} {'two'} {'buckle'} {'my'} {'shoe'}
>> c=cellfun(@flip,b,'un',0) % flip function applied to each cell (words)
c =
1×5 cell array
{'enO'} {'owt'} {'elkcub'} {'ym'} {'eohs'}
>> strM=strjoin(c) % cell array combined as one string array
strM =
'enO owt elkcub ym eohs'
>> bb=flip(strsplit(str,' ')) % flips the cell array
bb =
1×5 cell array
{'shoe'} {'my'} {'buckle'} {'two'} {'One'}
>> bbb=cellfun(@flip,bb,'un',0) % flip function applied to each cell (words)
bbb =
1×5 cell array
{'eohs'} {'ym'} {'elkcub'} {'owt'} {'enO'}
>> strN=strjoin(bbb) % cell array combined as one string array
strN =
'eohs ym elkcub owt enO'
>>
Samiha Shimla

### Samiha Shimla (view profile)

on 17 Jan 2019
Thanks a lot! This makes sense now! ^_^

on 17 Jan 2019
Anytime :)

### Sean de Wolski (view profile)

on 17 Jan 2019

str=join(reverse(split("One two buckle my shoe")))

Samiha Shimla

### Samiha Shimla (view profile)

on 17 Jan 2019
This is an excellent way of doing it! Thanks Sean!