Removing multiple blanks for a string

29 ビュー (過去 30 日間)
Jerry
Jerry 2013 年 10 月 30 日
コメント済み: Tushar Walse 2019 年 8 月 28 日
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

採用された回答

the cyclist
the cyclist 2013 年 10 月 30 日
txt_old = 'Tom and Jerry';
txt_new = regexprep(txt_old,' +',' ')
See
doc regexprep
for details.

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2013 年 10 月 30 日
regexprep() can do that.
Hint: diff()

Craig Szymanski
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 件のコメント
Stephen23
Stephen23 2019 年 8 月 28 日
編集済み: Stephen23 2019 年 8 月 28 日
"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
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).

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by