Function file that removes a character in a string?

20 views (last 30 days)
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.

Accepted Answer

Star Strider
Star Strider on 20 May 2018
This replaces the hyphen with a space.
You can use the loop if you want. You simply have to tweak it:
n = length(str);
for k = 1:n
if strfind(str(k),'-')
str(k) = ' ';
end
strOut = str;
end
A simpler implementation eliminates the loop entirely:
The loop is the problem. Just use strfind:
k = strfind(str,'-')
str(k) = ' ';
There are other functions that will do this more effieicntly (that I will let you search out).

More Answers (1)

Paolo
Paolo on 20 May 2018
Edited: Paolo on 21 May 2018
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 Comments
Stephen23
Stephen23 on 21 May 2018
Edited: Stephen23 on 21 May 2018
@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
Paolo on 21 May 2018
That's correct Stephen, thanks for pointing that out. The check is indeed redundant.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!