Removing multiple blanks for a string
이전 댓글 표시
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
채택된 답변
추가 답변 (2개)
Walter Roberson
2013년 10월 30일
0 개 추천
regexprep() can do that.
Hint: diff()
Craig Szymanski
2015년 5월 22일
A more direct andswer for anyone looking is:
function [strOut]=removeExtraSpaces(strIn);
temp2=strIn;
temp1='';
%Replaces double spaces with single spaces until the string doesn't change for an iteration.
while ~strcmp(temp1,temp2)
temp1=temp2;
temp2=regexprep(temp1,' ',' ');
end
strOut=temp2;
댓글 수: 4
Ilham Hardy
2015년 5월 22일
I failed to understand why is this more direct than regexprep. could explain a bit more?
Question: How are eight lines of code and a while-loop (containing strcmp and regexprep) more "direct" than one single call to regexprep?
Answer: they are not.
What this answer shows is a misunderstanding of how to use regular expressions effectively. The code uses
regexprep(temp1,' ',' ')
to replace any doubled space characters, but this ignores the ability of regular expressions to detect any number of space characters using the regular expression ' +', as per the cyclist's solution above and also the regular expression documentation.
"Actually ...isn't working for some combination of strings. May be its a bug..."
If you upload some example strings that show this behavior then we can check this, and most likely also suggest how to deal with it efficiently (i.e. without a while loop).
"regexprep... in a loop is good workaround"
Identifying and fixing the root cause is even better.
Tushar Walse
2019년 8월 28일
Sorry my mistake. I realized the problem was when displaying strings in multiline edit box ghost spaces get displayed which I thought are coming from the output of regexprep. I may sound completely stupid sorry again. Also I deleted the comment (seems I committed another stupid mistake).
카테고리
도움말 센터 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!