MATLAB: Removing multiple blanks for a string

blankisspaceMATLABspacestrings

suppose I have a string mystr='Tom and Jerry' I want to write a function that removes all the spaces and leaves just one space in between each word. So I would want the outcome to be 'Tom and Jerry' I used mystr=mystr(~isspace(mystr)) and got TomandJerry but how would I include one space in bettween each word? Thank you

Best Answer

txt_old = 'Tom and Jerry';
txt_new = regexprep(txt_old,' +',' ')
See
doc regexprep
for details.