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","")
y =
"abc "
>> y=strrep(x,'defg','')
y =
"abc "
y=strrep(x,'defg',char([]))
y =
"abc "
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", [])
Warning: Inputs must be character vectors, cell arrays of character vectors, or string arrays.
y =
"abc "
>> y = strrep(x,"defg", string([]))
y =
0×0 empty string array
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 Comment
Stephen Cobeldick (view profile)
Direct link to this comment
https://de.mathworks.com/matlabcentral/answers/463135-strrep-is-inconsistent-with-empty-replacement-strings#comment_711612
Sign in to comment.