Info
Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.
How can I replace the tag with the given replacement without using strrep
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Walter Roberson
am 3 Dez. 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() ?
Walter Roberson
am 3 Dez. 2019
What is the difference between this question and your earlier https://www.mathworks.com/matlabcentral/answers/494453-how-will-i-replace-a-string-with-another-string-without-using-strrep ? I think this question should have been part of the earlier one.
Antworten (0)
Diese Frage ist geschlossen.
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!