remove to only one whitespace in a string

hi all, I am writing a function that to remove the blanks between the words and return it to only one space. like
mystr = 'Lets go party'
Return to
remove_blanks(mystr) = 'Lets go party'
So far, I got mystr = 'Lets go party'; function remove_blanks(mystr) y = mystr(isspace(mystr))='';
I know how to remove all the space between the words but I don't know how to remove to one left.

 採用された回答

Orion
Orion 2014 年 11 月 11 日
編集済み: Orion 2014 年 11 月 11 日

3 投票

Hi,
you need to use a regular expression
mystr = 'Lets go party';
mystr = regexprep(mystr,'\s+',' ');
% \s+ means multiple spaces
mystr =
Lets go party

3 件のコメント

jarvan
jarvan 2014 年 11 月 12 日
ya..I'm required to use function to do this, but your code works for me how should I change if I have to use function to do this?
Guillaume
Guillaume 2014 年 11 月 12 日
It's not clear what you're asking. regexp is a function.
Orion
Orion 2014 年 11 月 12 日
just do a function :
function cleanstr = remove_blanks(mystr)
cleanstr = regexprep(mystr,'\s+',' ');

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

その他の回答 (1 件)

Guillaume
Guillaume 2014 年 11 月 11 日

0 投票

A regular expression is the simplest way to do that. Otherwise you can always strsplit the string (which ignores multiple spaces by default) and strjoin it back.

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

質問済み:

2014 年 11 月 11 日

コメント済み:

2014 年 11 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by