MATLAB Answers

how will I replace a string with another string without using strrep?

10 views (last 30 days)
Hanna Dulay
Hanna Dulay on 3 Dec 2019
Commented: Walter Roberson on 3 Dec 2019
function newstring = replace_tags(readstring,tag,replacement);
newstring = "";
r_s=lower(readstring);
i= strfind(r_s,tag);
tg=i+length(tag);
final=readstring(i:tg)
end
This is my code so far.

Answers (2)

Bhaskar R
Bhaskar R on 3 Dec 2019
Can I use regexprep command ??, If yes
function newstring = replace_tags(readstring,tag,replacement)
r_s=lower(readstring);
% By regular expression
newstring = regexprep(r_s, tag, replacement); % you can do lot of stuff by this
end

  0 Comments

Sign in to comment.


Erivelton Gualter
Erivelton Gualter on 3 Dec 2019
If you still want to keep your line of thought instead of using Bhaskar approach, which is simpler, you can:
% Example entries
readstring = 'This is a good example';
tag = 'good';
replacement = 'great';
% Test
newstring = replace_tags(readstring,tag,replacement)
% Function
function newstring = replace_tags(readstring, tag, replacement)
i = strfind(lower(readstring),tag);
tg = i+length(tag);
newstring = [readstring(1:i-1), replacement, readstring(tg:end)];
end

  0 Comments

Sign in to comment.

Sign in to answer this question.

Tags