Function file that removes a character in a string?
이전 댓글 표시
So I'm tasked to make a function file that removes a dash (-) from a string, and I'm not allowed to use strrep for some reason (kinda dumb because the code works completely fine with strrep). Regardless, this is my attempt at the code:
function [strOut] = RemoveDash(str)
% This function takes a string and returns that same string without a dash.
n = length(str);
for k = 1:n
if str(k) == strfind(str,'-')
str(k) = [];
end
strOut = str;
end
end
What I want is, if I enter a string 'first-dash', it'll return 'firstdash'. Instead, nothing changes for me:
strOut = RemoveDash('first-dash')
strOut =
'first-dash'
What am I missing in my function code? My input string seems to ignore the loop and just output the same input string. Help would be appreciated.
채택된 답변
추가 답변 (1개)
Two alternatives if you are not allowed to use strrep.
function [strOut] = RemoveDash(str)
k = strfind(str,'-');
str(k) = [];
strOut = str;
end
Or
function [strOut] = RemoveDash(str)
strOut=regexprep(str,'-','');
end
EDIT.
As pointed out by Star Strider in his answer and by Stephen in the comment below, the check is indeed redundant as an empty index does not throw any errors. I have removed the conditional branch from the first example.
댓글 수: 2
@Paolo Lazzari: Using indexing like this is likely to be much more efficient than using a loop, so this is a valid and useful suggestion. Note that the first function does not actually return the altered string, and the if is not required because using an empty index is not an error. Perhaps you meant this?:
function str = RemoveDash(str)
k = strfind(str,'-');
str(k) = [];
end
Paolo
2018년 5월 21일
That's correct Stephen, thanks for pointing that out. The check is indeed redundant.
카테고리
도움말 센터 및 File Exchange에서 App Building에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!