Using a loop to replace spaces for underscore
Mostrar comentarios más antiguos
Hello there, I am a complete begginer in Matlab and was given an exercise that took me a whole day and still, no success.
The following function puts a '\' in front of every underscore. I have to change this function in a way that it replaces every space for an underscore.
locs = strfind(instring, '_'); % finding all underscores
if isempty(locs)
outstring = instring;
else
outstring_start_ind = 1;
instring_start_ind = 1;
for underscore_cnt = 1:length(locs) % for each underscores
outstring(outstring_start_ind:(locs(underscore_cnt)+underscore_cnt-2)) = ...
instring(instring_start_ind:(locs(underscore_cnt)-1));
outstring(locs(underscore_cnt)+underscore_cnt-1) = '\';
outstring_start_ind = locs(underscore_cnt)+underscore_cnt;
instring_start_ind = locs(underscore_cnt);
end
outstring(outstring_start_ind:(length(instring)+underscore_cnt)) = ...
instring(instring_start_ind:end);
end
Is there someone who can give me a hand here, please? Thank you.
6 comentarios
Laura Mendes
el 12 de Jun. de 2021
Jonas
el 12 de Jun. de 2021
if you want to replace every space with an underscore you could call
strOut=strrep(strIn,' ','_');
Laura Mendes
el 12 de Jun. de 2021
Laura Mendes
el 12 de Jun. de 2021
Laura Mendes
el 13 de Jun. de 2021
Respuestas (2)
John D'Errico
el 12 de Jun. de 2021
Ye gods, that is a complicated way to solve a job poorly. Sorry, but it is. Two lines, assuming you want the result in outstring. One line, if you are willing to replace in the original string.
outstring = instring;
outstring(instring == '_') = ' ';
That replaces every underscore with a space.
1 comentario
Laura Mendes
el 13 de Jun. de 2021
Use the replace function.
before = 'Hello world'
after = replace(before, ' ', ' cruel ')
1 comentario
Laura Mendes
el 13 de Jun. de 2021
Categorías
Más información sobre MATLAB en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!