Using a loop to replace spaces for underscore

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

Jonas
Jonas 2021년 6월 12일
편집: Jonas 2021년 6월 12일
do you have to use the basic structure of the given function? if not, just use the strrep() function which replaces a specific character array by another
ok, thank you very much. could you show me how would I use it ?
if you want to replace every space with an underscore you could call
strOut=strrep(strIn,' ','_');
Ok, thank you. But actually I should use the basic structure of the function I posted. Do you have ideas? Thank you
I tried this function within the main code where I use the posted function, and it did not work... :/
I did it thank u very much

댓글을 달려면 로그인하십시오.

답변 (2개)

John D'Errico
John D'Errico 2021년 6월 12일

0 개 추천

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

I had to change something here, but it HELPED! Thank you so much for the support!

댓글을 달려면 로그인하십시오.

Steven Lord
Steven Lord 2021년 6월 12일
Use the replace function.
before = 'Hello world'
before = 'Hello world'
after = replace(before, ' ', ' cruel ')
after = 'Hello cruel world'

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

제품

질문:

2021년 6월 12일

댓글:

2021년 6월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by