Replacing Occurrences of String?

(Ajay deleted this so I (MF) am restoring it)
How do I replace every instance of 'str1' in a input sentence? My function (ReplaceStrAll) should return the intact input sentence as its output, if it cannot find any occurrence of str1 in the input sentence.
This is the code I wrote:
function output_sentence = ReplaceStrAll(input_sentence, str1, str2)
str1_index = strfind(input_sentence,str1);
output_sentence = [input_sentence(1:str1_index(1)-1),str2,... input_sentence( str1_index(1)+length(str1):length(input_sentence) )];
what is wrong with it? I already got verification that I'm on the right path and I just need to make a few adjustments, but what am I messing up in the code?

댓글 수: 3

Walter Roberson
Walter Roberson 2012년 10월 8일
What problem are you observing with the code?
Walter Roberson
Walter Roberson 2012년 10월 8일
Content of the question was edited out of existence by the original poster :(
Matt Fig
Matt Fig 2012년 10월 9일
Saved from google cache:
How do I replace every instance of 'str1' in a input sentence? My function (ReplaceStrAll) should return the intact input sentence as its output, if it cannot fi nd any occurrence of str1 in the input sentence.
This is the code I wrote:
function output_sentence = ReplaceStrAll(input_sentence, str1, str2) str1_index = strfind(input_sentence,str1); output_sentence = [input_sentence(1:str1_index(1)-1),str2,... input_sentence( str1_index(1)+length(str1):length(input_sentence) )];
what is wrong with it? I already got verification that I'm on the right path and I just need to make a few adjustments, but what am I messing up in the code?

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

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 10월 8일
편집: Andrei Bobrov 2012년 10월 8일

0 개 추천

please try this is code:
out = input_sentence;
ii = strfind(out,str1)
if ~isempty(ii)
for ii = ii
out = [out(1:ii-1),str2,out(ii+numel(str1):end)];
end
end
or
out = input_sentence;
[i1,i2] = regexp(out,str1);
if ~isempty(i1)
for ii = 1:numel(i1)
out = [out(1:i1(ii)-1),str2,out(i2(ii)+1:end)];
end
end
or
out = regexprep(input_sentence,str1,str2);
or
out = strrep(input_sentence,str1,str2);

댓글 수: 1

Ajay
Ajay 2012년 10월 8일
thanks you figured it out with the regexprep!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Troubleshooting in Polyspace Products for Ada에 대해 자세히 알아보기

질문:

2012년 10월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by