Info

この質問は閉じられています。 編集または回答するには再度開いてください。

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

1 回表示 (過去 30 日間)
Hanna Dulay
Hanna Dulay 2019 年 12 月 3 日
閉鎖済み: Stephen23 2019 年 12 月 3 日
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
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
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!

Translated by