Info
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
How can I replace the tag with the given replacement without using strrep
조회 수: 2 (최근 30일)
이전 댓글 표시
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
Walter Roberson
2019년 12월 3일
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
2019년 12월 3일
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.
답변 (0개)
이 질문은 마감되었습니다.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!