Function file that removes a character in a string?
12 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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.
0 Commenti
Risposta accettata
Star Strider
il 20 Mag 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).
0 Commenti
Più risposte (1)
Paolo
il 20 Mag 2018
Modificato: Paolo
il 21 Mag 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 Commenti
Stephen23
il 21 Mag 2018
Modificato: Stephen23
il 21 Mag 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
il 21 Mag 2018
That's correct Stephen, thanks for pointing that out. The check is indeed redundant.
Vedere anche
Categorie
Scopri di più su Matrices and Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!