strsplit: the deliminator on both sides was still kept but not removed

9 ビュー (過去 30 日間)
raym
raym 2021 年 9 月 19 日
コメント済み: dpb 2021 年 9 月 20 日
Hi,
I am using strsplit to split a string by space using R2016a. I expect all the space was removed, but I got:
strsplit(' aa bb cc ',' ')
ans = '' 'aa' 'bb' 'cc' ''
Is this results supposed to be, or is there something wrong with the installed version of matlab on this PC(e.g., hard drive hitted by cosmic rays so some library was corrupted)? Thus I tried Matlab online and got the same results:
a = strsplit(' aa bb cc ',' ')
a =
1×5 cell array
{0×0 char} {'aa'} {'bb'} {'cc'} {0×0 char}
It's confusing that the 0×0 char was returned. on the left and right most slde
Thanks.

採用された回答

dpb
dpb 2021 年 9 月 19 日
編集済み: dpb 2021 年 9 月 20 日
WAD (Working As Designed)
>> a = strsplit(' aa bb cc ',' ')
a =
1×5 cell array
{0×0 char} {'aa'} {'bb'} {'cc'} {0×0 char}
>> a = strsplit(strtrim(' aa bb cc '),' ')
a =
1×3 cell array
{'aa'} {'bb'} {'cc'}
>>
The delimiter comes first and last in the original input string -- that there isn't anything before or after is not important to strsplit; it creates a field based on the number of delimited fields in the string, not on the content of those fields.
If you don't want the leading/trailing blanks to be significant, remove them first as shown.
  1 件のコメント
dpb
dpb 2021 年 9 月 20 日
I have often (occasionally?) wished for an enhancement that would work with variable number of delimiters in the records in the input cell array

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

その他の回答 (0 件)

カテゴリ

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