MATLAB Answers

Info

This question is closed.

How can I replace the tag with the given replacement without using strrep

2 views (last 30 days)
Hanna Dulay
Hanna Dulay on 3 Dec 2019
Closed: Stephen Cobeldick on 3 Dec 2019
Here is my code
function [] = ()
clc;clear
readstring = read_form('form.txt');
[tag,replacement] = read_sub_tag();
newstring = replace_tags(readstring,tag,replacement);
create_output('Tongue_Twister.txt',newstring)
end
function readstring = read_form(textfile)
readstring = []; %empty readstring
text=fopen(textfile,'r');
if text==-1 %Check if the file opened correctly
sprintf('File not correctly open')
else
while ~ feof(text) %to read until the end
txt=fgets(text); %read every single line
readstring=sprintf('%s\r',readstring,txt);
readstring=strcat(readstring);%concatenate the lines into string
end
end
fclose(text);
return
end
function [tag,replacement] = read_sub_tag()
tag = []; %empty tag
replacement = []; %empty replacement
sub_tag=fopen('sub.txt','r');
if sub_tag==-1 %check if the file opened correctly
sprintf('File not correctly opened')
else
while feof(sub_tag)==0
sub=fgetl(sub_tag);
[tag,replacement]=strtok(sub); %to create separate arrays for the tag and replacement
tag=lower(tag);
replacement=strtrim(replacement);
end
end
fclose(sub_tag);
return
end
function newstring = replace_tags(readstring,tag,replacement)
newstring = "";
r_s=lower(readstring);
i= strfind(r_s,tag);
tg=i+length(tag);
splitlines(readstring);
for final=readstring(i:tg)
newstring=replace(readstring,final,replacement);
end
return
end
function create_output('Tongue_Twister.txt';newstring)
name=fopen('Tongue_Twister.txt,''wt');
fprintf(name,newstring);
fclose(name);
end

  2 Comments

Walter Roberson
Walter Roberson on 3 Dec 2019
You already are. replace() is not strrep()
However, notice you have
for final=readstring(i:tg)
newstring=replace(readstring,final,replacement);
end
You are not modifying readstring or replacement in the loop, so each iteration is just going to overwrite newstring and the result is going to be as-if you had only done the final iteration.
Your readstring variable appears to be a character vector, so your for loop is going to be proceeding character by character rather than word by word.
By the way, instead of that looping code in read_form, why not just use fileread() ?

Answers (0)

Tags