strrep is inconsistent with empty replacement strings
조회 수: 15 (최근 30일)
이전 댓글 표시
I have reported this as a bug. strrep responds differently when the replacement string is various flavors of empty.
'Proper' ways to do this:
x = "abc defg";
>> y = strrep(x,"defg","") % with an empty string object
y =
"abc " % expected result
>> y=strrep(x,'defg','') % with an empty char array
y =
"abc " % same result
y=strrep(x,'defg',char([])) % with an empty char array
y =
"abc " % also same result
One might be tempted to use [ ] or string([ ]) as the replacement string, especially if working with something like a class member that is initialized to empty. But using the first produces the expected result (but with a warning), while using the second unexpectedly clears the entire return value:
>> y = strrep(x,"defg", []) % with an empty array
Warning: Inputs must be character vectors, cell arrays of character vectors, or string arrays.
y =
"abc " % same result, but with warning...
>> y = strrep(x,"defg", string([])) % with an empty string array
y =
0×0 empty string array % ouch! why is this one different?
It would be nice in Matlab would either treat [ ] and string([ ]) the same as "", '' and char( [ ] ), or throw an error so code aborts when handed an unexpected data type.
답변 (1개)
Shivam Sardana
2019년 5월 29일
“string([])” is an empty string array, not a scalar string array with no characters in it. strrep retains the shape of its non-scalar inputs. To get the expected result i.e. "abc ", provide a scalar string with no characters in it:
y = strrep(x,"defg", string(['']))
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!