Function file that removes a character in a string?

12 visualizaciones (últimos 30 días)
Emanuele Joy
Emanuele Joy el 20 de Mayo de 2018
Editada: Paolo el 21 de Mayo de 2018
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.

Respuesta aceptada

Star Strider
Star Strider el 20 de Mayo de 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).

Más respuestas (1)

Paolo
Paolo el 20 de Mayo de 2018
Editada: Paolo el 21 de Mayo de 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 comentarios
Stephen23
Stephen23 el 21 de Mayo de 2018
Editada: Stephen23 el 21 de Mayo de 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 el 21 de Mayo de 2018
That's correct Stephen, thanks for pointing that out. The check is indeed redundant.

Iniciar sesión para comentar.

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by